C# List集合去重使用lambda表达式

name age sex
Lucy 22 woman
Lily 23 woman
Tom 24 man
Lucy 22 woman
Lily 23 woman
LiLei 25 man
List<Person> list_persons = new List<Person>(new Person("Lucy",22,"woman"),new Person("Lily",23,"woman"),new Person("Tom",24,"man"),new Person("Lucy",22,"woman"),new Person("Lily",23,"woman"),new Person("LiLei",25,"man"));

如同上表中,名字(name)中重复的想要去除,使用linq进行去重的方法,使用Distinct()根本无法达到要求。那么:

var list_distinct = list_Persons.GroupBy(c => c.name).Select(c => c.First());

实际的意思是根据某一列进行分组,然后获取每一组的第一条数据,可以解决此次需求

猜你喜欢

转载自blog.csdn.net/shan1774965666/article/details/81390209