我玩LINQ来了解它,但我不知道如何使用鲜明当我没有一个简单的列表(一个简单的整数列表是很容易做到的,这不是问题)。如果我想使用鲜明的列表<TElement>上的一个或多个属性的TElement?

示例:如果一个对象是Person,具有属性Id。我怎么能得到所有人,并使用鲜明对他们与对象的属性Id ?

Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"

如何得到Person1和Person3?这可能吗?

如果用LINQ是不可能的,那么根据Person的某些属性获得Person列表的最佳方法是什么?


当前回答

也许这个能帮上忙,试试这个。使用HashSet可以提高代码性能。

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    var known = new HashSet<TKey>();
    return source.Where(element => known.Add(keySelector(element)));
}

其他回答

如果您需要在多个属性上使用Distinct方法,您可以查看我的PowerfulExtensions库。目前它在一个非常年轻的阶段,但你已经可以使用方法,如明确,联合,相交,除任何数量的属性;

下面是它的用法:

using PowerfulExtensions.Linq;
...
var distinct = myArray.Distinct(x => x.A, x => x.B);

下面的代码在功能上等同于Jon Skeet的答案。

在. net 4.5上测试,应该可以在任何早期版本的LINQ上运行。

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
  this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
  HashSet<TKey> seenKeys = new HashSet<TKey>();
  return source.Where(element => seenKeys.Add(keySelector(element)));
}

顺便说一句,请在谷歌Code上查看Jon Skeet的最新版本的DistinctBy.cs。

更新2022-04-03

根据Andrew McClement的评论,最好接受John Skeet的回答。

当我们在项目中面临这样的任务时,我们定义了一个小API来组合比较器。

所以,用例是这样的:

var wordComparer = KeyEqualityComparer.Null<Word>().
    ThenBy(item => item.Text).
    ThenBy(item => item.LangID);
...
source.Select(...).Distinct(wordComparer);

API本身是这样的:

using System;
using System.Collections;
using System.Collections.Generic;

public static class KeyEqualityComparer
{
    public static IEqualityComparer<T> Null<T>()
    {
        return null;
    }

    public static IEqualityComparer<T> EqualityComparerBy<T, K>(
        this IEnumerable<T> source,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc);
    }

    public static KeyEqualityComparer<T, K> ThenBy<T, K>(
        this IEqualityComparer<T> equalityComparer,
        Func<T, K> keyFunc)
    {
        return new KeyEqualityComparer<T, K>(keyFunc, equalityComparer);
    }
}

public struct KeyEqualityComparer<T, K>: IEqualityComparer<T>
{
    public KeyEqualityComparer(
        Func<T, K> keyFunc,
        IEqualityComparer<T> equalityComparer = null)
    {
        KeyFunc = keyFunc;
        EqualityComparer = equalityComparer;
    }

    public bool Equals(T x, T y)
    {
        return ((EqualityComparer == null) || EqualityComparer.Equals(x, y)) &&
                EqualityComparer<K>.Default.Equals(KeyFunc(x), KeyFunc(y));
    }

    public int GetHashCode(T obj)
    {
        var hash = EqualityComparer<K>.Default.GetHashCode(KeyFunc(obj));

        if (EqualityComparer != null)
        {
            var hash2 = EqualityComparer.GetHashCode(obj);

            hash ^= (hash2 << 5) + hash2;
        }

        return hash;
    }

    public readonly Func<T, K> KeyFunc;
    public readonly IEqualityComparer<T> EqualityComparer;
}

更多细节请访问我们的网站:iequalitycompararer in LINQ。

如果你不想将MoreLinq库添加到你的项目中只是为了获得DistinctBy功能,那么你可以使用重载Linq的Distinct方法获得相同的最终结果,该方法采用了一个IEqualityComparer参数。

首先创建一个通用的自定义相等比较器类,它使用lambda语法对一个泛型类的两个实例进行自定义比较:

public class CustomEqualityComparer<T> : IEqualityComparer<T>
{
    Func<T, T, bool> _comparison;
    Func<T, int> _hashCodeFactory;

    public CustomEqualityComparer(Func<T, T, bool> comparison, Func<T, int> hashCodeFactory)
    {
        _comparison = comparison;
        _hashCodeFactory = hashCodeFactory;
    }

    public bool Equals(T x, T y)
    {
        return _comparison(x, y);
    }

    public int GetHashCode(T obj)
    {
        return _hashCodeFactory(obj);
    }
}

然后在你的主代码中这样使用它:

Func<Person, Person, bool> areEqual = (p1, p2) => int.Equals(p1.Id, p2.Id);

Func<Person, int> getHashCode = (p) => p.Id.GetHashCode();

var query = people.Distinct(new CustomEqualityComparer<Person>(areEqual, getHashCode));

瞧!:)

以上假设如下:

财产的人。Id的类型是int people集合不包含任何空元素

如果集合可能包含空值,那么只需重写lambdas来检查空值,例如:

Func<Person, Person, bool> areEqual = (p1, p2) => 
{
    return (p1 != null && p2 != null) ? int.Equals(p1.Id, p2.Id) : false;
};

EDIT

这种方法与弗拉基米尔·涅斯特罗夫斯基的答案相似,但更简单。

它也类似于Joel的回答,但允许涉及多个属性的复杂比较逻辑。

然而,如果你的对象只能因Id而不同,那么另一个用户给出了正确的答案,你所需要做的就是在你的Person类中覆盖GetHashCode()和Equals()的默认实现,然后只使用Linq的开箱即开的Distinct()方法来过滤掉任何重复。

您可以使用标准Linq.ToLookup()来实现这一点。这将为每个唯一键创建一个值集合。只需选择集合中的第一项

Persons.ToLookup(p => p.Id).Select(coll => coll.First());