using DailyCoding.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DailyCoding.Code { [ClassInfo("List遍历删除重复元素")] public class _20210515_1 { public void Run() { var list = new List<_20210515_1_Model>(); list.Add(new _20210515_1_Model { Id = 1, Name = "N1", Addr = "A1" }); list.Add(new _20210515_1_Model { Id = 1, Name = "N1", Addr = "A1" }); list.Add(new _20210515_1_Model { Id = 2, Name = "N2", Addr = "A2" }); list.Add(new _20210515_1_Model { Id = 2, Name = "N2", Addr = "A2" }); list.Add(new _20210515_1_Model { Id = 3, Name = "N3", Addr = "A3" }); list.Add(new _20210515_1_Model { Id = 3, Name = "N3", Addr = "A3" }); // 根据id值去重 var idDistinctList = list.GroupBy(t => t.Id).Select(t => t.First()); // 从后往前遍历,删除 Name和Addr 重复的元素 for (int i = list.Count - 1; i >= 0; i--) { if (list.Where(t => t.Name == list[i].Name && t.Addr == list[i].Addr).Count() > 1) list.RemoveAt(i); } } } public class _20210515_1_Model { public int Id { get; set; } public string Name { get; set; } public string Addr { get; set; } } }
原文:https://www.cnblogs.com/tomorrow0/p/14771906.html