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

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

问题描述

我正在使用 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"

我怎样才能只得到 Person1Person3?这可能吗?

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?

推荐答案

编辑:这现在是 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屋!

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