如何从列表中获取不同的数据? [英] How to get the distinct data from a list?

查看:95
本文介绍了如何从列表中获取不同的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从人员列表中获取与众不同列表.

I want to get distinct list from list of persons .

List<Person> plst = cl.PersonList;

如何通过LINQ执行此操作.我想将结果存储在List<Person>

How to do this through LINQ. I want to store the result in List<Person>

推荐答案

Distinct()将为您提供不同的值-但除非您覆盖了Equals/GetHashCode(),否则您将仅获得不同的引用.例如,如果您希望两个Person对象的名称相等,则它们相等,则需要覆盖Equals/GetHashCode来表明这一点. (理想情况下,实现IEquatable<Person>以及仅覆盖Equals(object).)

Distinct() will give you distinct values - but unless you've overridden Equals / GetHashCode() you'll just get distinct references. For example, if you want two Person objects to be equal if their names are equal, you need to override Equals/GetHashCode to indicate that. (Ideally, implement IEquatable<Person> as well as just overriding Equals(object).)

然后您需要调用ToList()以将结果作为List<Person>取回:

You'll then need to call ToList() to get the results back as a List<Person>:

var distinct = plst.Distinct().ToList();

如果您想通过某些特定的属性来吸引不同的人,但是这不是自然"平等的合适人选,则您要么需要像这样使用GroupBy:

If you want to get distinct people by some specific property but that's not a suitable candidate for "natural" equality, you'll either need to use GroupBy like this:

var people = plst.GroupBy(p => p.Name)
                 .Select(g => g.First())
                 .ToList();

或使用 MoreLINQ 中的DistinctBy方法:

var people = plst.DistinctBy(p => p.Name).ToList();

这篇关于如何从列表中获取不同的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆