LINQ 对特定属性的 Distinct() [英] LINQ's Distinct() on a particular property
问题描述
我正在使用 LINQ 来了解它,但是当我没有一个简单的列表(一个简单的整数列表很容易做到)时,我无法弄清楚如何使用 Distinct
,这不是问题).如果我想使用 Distinct 在对象的一个或更多个属性的对象列表上?
I am playing with LINQ to learn about it, but I can't figure out how to use Distinct
when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?
示例:如果对象是 Person
,具有属性 Id
.如何使用对象的属性 Id
获取所有 Person 并在其上使用 Distinct
?
Example: If an object is Person
, with Property Id
. How can I get all Person and use Distinct
on them with the property Id
of the object?
Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
我怎样才能获得 Person1
和 Person3
?这可能吗?
How can I get just Person1
and Person3
? Is that possible?
如果 LINQ 无法实现,那么根据 .NET 3.5 中的某些属性获得 Person
列表的最佳方法是什么?
If it's not possible with LINQ, what would be the best way to have a list of Person
depending on some of its properties in .NET 3.5?
推荐答案
EDIT:这现在是 MoreLINQ.
您需要的是有效的distinct-by".我不认为它是 LINQ 的一部分,尽管它很容易编写:
What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
因此要仅使用 Id
属性查找不同的值,您可以使用:
So to find the distinct values using just the Id
property, you could use:
var query = people.DistinctBy(p => p.Id);
并且要使用多个属性,您可以使用匿名类型,它们适当地实现了相等性:
And to use multiple properties, you can use anonymous types, which implement equality appropriately:
var query = people.DistinctBy(p => new { p.Id, p.Name });
未经测试,但它应该可以工作(现在至少可以编译).
Untested, but it should work (and it now at least compiles).
它假定键的默认比较器 - 如果你想传入一个相等比较器,只需将它传递给 HashSet
构造函数.
It assumes the default comparer for the keys though - if you want to pass in an equality comparer, just pass it on to the HashSet
constructor.
这篇关于LINQ 对特定属性的 Distinct()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!