51

我想获取列表中的不同值,但不是通过标准相等比较。

我想做的是这样的:

return myList.Distinct( (x, y) => x.Url == y.Url );

我不能,Linq 中没有扩展方法可以做到这一点 - 只有一个需要IEqualityComparer.

我可以用这个破解它:

return myList.GroupBy( x => x.Url ).Select( g => g.First() );

但这似乎很混乱。它也不完全做同样的事情——我只能在这里使用它,因为我只有一个键。

我也可以添加我自己的:

public static IEnumerable<T> Distinct<T>( 
    this IEnumerable<T> input, Func<T,T,bool> compare )
{
    //write my own here
}

但这似乎更像是在写一些本来就应该存在的东西。

有人知道为什么没有这种方法吗?

我错过了什么吗?

4

4 回答 4

58

这很烦人,当然。它也是我的“MoreLINQ”项目的一部分,在某些时候我必须注意 :) 有很多其他操作在对投影进行操作时是有意义的,但要返回原始的 MaxBy 和 MinBy 会浮现在脑海中。

正如您所说,它很容易编写 - 尽管我更喜欢名称“DistinctBy”来匹配 OrderBy 等。如果您有兴趣,这是我的实现:

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source,
         Func<TSource, TKey> keySelector)
    {
        return source.DistinctBy(keySelector,
                                 EqualityComparer<TKey>.Default);
    }

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source,
         Func<TSource, TKey> keySelector,
         IEqualityComparer<TKey> comparer)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }
        if (keySelector == null)
        {
            throw new ArgumentNullException("keySelector");
        }
        if (comparer == null)
        {
            throw new ArgumentNullException("comparer");
        }
        return DistinctByImpl(source, keySelector, comparer);
    }

    private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>
        (IEnumerable<TSource> source,
         Func<TSource, TKey> keySelector,
         IEqualityComparer<TKey> comparer)
    {
        HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
        foreach (TSource element in source)
        {
            if (knownKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }
于 2009-02-06T12:00:34.927 回答
36

但这似乎很混乱。

这不是乱七八糟,是正确的。

  • 如果你想要DistinctProgrammers by FirstName 并且有四个 Amy,你想要哪一个?
  • 如果你Group的程序员 By FirstName 并拿了First一个,那么在四个 Amy 的情况下你想做什么就很清楚了。

我只能在这里使用它,因为我只有一个键。

您可以使用相同的模式执行多个键“不同”:

return myList
  .GroupBy( x => new { x.Url, x.Age } )
  .Select( g => g.First() );
于 2009-02-06T13:38:56.087 回答
3

乔恩,你的解决方案非常好。一个小小的变化。我认为我们不需要 EqualityComparer.Default 。这是我的解决方案(当然起点是 Jon Skeet 的解决方案)

    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
    {
        //TODO All arg checks
        HashSet<TKey> keys = new HashSet<TKey>();
        foreach (T item in source)
        {
            TKey key = keySelector(item);
            if (!keys.Contains(key))
            {
                keys.Add(key);
                yield return item;
            }
        }
    }
于 2010-10-08T18:29:26.863 回答
2

使用 AmyB 的答案,我编写了一个小的DistinctBy扩展方法,以允许传递谓词:

/// <summary>
/// Distinct method that accepts a perdicate
/// </summary>
/// <typeparam name="TSource">The type of the t source.</typeparam>
/// <typeparam name="TKey">The type of the t key.</typeparam>
/// <param name="source">The source.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>IEnumerable&lt;TSource&gt;.</returns>
/// <exception cref="System.ArgumentNullException">source</exception>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> predicate)
{
    if (source == null)
        throw new ArgumentNullException("source");

    return source
        .GroupBy(predicate)
        .Select(x => x.First());
}

您现在可以传递谓词以通过以下方式对列表进行分组:

var distinct = myList.DistinctBy(x => x.Id);

或按多个属性分组:

var distinct = myList.DistinctBy(x => new { x.Id, x.Title });
于 2016-09-01T08:02:13.713 回答