LINQ的鲜明()上的特定属性 [英] LINQ's Distinct() on a particular property

查看:162
本文介绍了LINQ的鲜明()上的特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与LINQ打去了解它,但我无法弄清楚如何使用DISTINCT时,我没有一个简单的列表(整数一个简单的列表是pretty容易做到的,这是不是这个问题)。我如果想使用<一个href=\"https://msdn.microsoft.com/library/system.linq.enumerable.distinct%28v=vs.100%29.aspx\">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?

例如:如果一个对象是,与地产编号。我怎样才能让所有的人,并使用鲜明它们与对象的属性编号

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人列表的最佳方法是什么?

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?

推荐答案

修改:这是现在 MoreLINQ的一部分

您需要的是一个独特的,以有效。我不相信这是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;
        }
    }
}

因此​​,要找到只使用编号属性不同的值,可以使用:

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的鲜明()上的特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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