注意 下面的代码只要ID相同(即使其他的不相同)都会过滤掉,简单来讲就是过滤掉ID相同的实体,如果ID相同,其他属性取第一个的值
List<Abc> list = new List<Abc>(); Abc abc1 = new Abc(); abc1.Id = 1; abc1.Name = "张三"; abc1.Value = "a"; list.Add(abc1); Abc abc2 = new Abc(); abc2.Id = 1; abc2.Name = "张三"; abc2.Value = "b"; list.Add(abc2); Abc abc3 = new Abc(); abc3.Id = 1; abc3.Name = "张三"; abc3.Value = "a"; list.Add(abc3); Abc abc4 = new Abc(); abc4.Id = 1; abc4.Name = "张三"; abc4.Value = "e"; list.Add(abc4); Abc abc5 = new Abc(); abc5.Id = 1; abc5.Name = "张三"; abc5.Value = "c"; list.Add(abc5); list = list.GroupBy(o => o.Id).Select(p => new Abc { Id = p.Key, Name = p.FirstOrDefault().Name, Value = p.FirstOrDefault().Value }).ToList();
结果 只有 list.count=1 id=1,Name="张三", Value="a"