鲜明的Linq在一个特定的属性 [英] Linq Distinct on a particular Property

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

问题描述

我玩的LINQ学习一下吧,但我不知道如何使用DISTINCT时,我没有一个简单的列表(整数一个简单的列表是pretty的容易做到的,这并不是题)。如果想使用分明对象对对象的一个​​或多个属性的列表上?

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 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天全站免登陆