你能用lambda表达式创建一个简单的'EqualityComparer <T>'

Sim*_*ver 39 c# linq distinct

重要提示:这不是LINQ-to-SQL问题.这是对象的LINQ.

简短的问题:

LINQ中是否有一种简单的方法可以根据对象的键属性从列表中获取不同的对象列表.

长问题:

我正在尝试对具有键作为其属性之一的对象Distinct()列表执行操作.

class GalleryImage {
   public int Key { get;set; }
   public string Caption { get;set; }
   public string Filename { get; set; }
   public string[] Tags {g et; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个Gallery包含的对象列表GalleryImage[].

由于web服务的工作方式[原文如此],我有GalleryImage对象的重复 .我认为用它Distinct()来获得一个独特的列表是一件简单的事情.

这是我想要使用的LINQ查询:

var allImages = Galleries.SelectMany(x => x.Images);
var distinctImages = allImages.Distinct<GalleryImage>(new 
                     EqualityComparer<GalleryImage>((a, b) => a.id == b.id));
Run Code Online (Sandbox Code Playgroud)

问题是这EqualityComparer是一个抽象类.

我不想:

  • 实现IEquatable,GalleryImage因为它是生成的
  • 必须编写一个单独的类来实现IEqualityComparer,如下所示

是否有一个EqualityComparer我缺少的具体实现?

我原本以为会有一种简单的方法可以根据键从一组中获取"不同"的对象.

Jon*_*eet 38

(这里有两种解决方案 - 见第二种解决方案):

我的MiscUtil库有一个ProjectionEqualityComparer类(以及两个支持类来使用类型推断).

以下是使用它的示例:

EqualityComparer<GalleryImage> comparer = 
    ProjectionEqualityComparer<GalleryImage>.Create(x => x.id);
Run Code Online (Sandbox Code Playgroud)

这是代码(删除了评论)

// Helper class for construction
public static class ProjectionEqualityComparer
{
    public static ProjectionEqualityComparer<TSource, TKey>
        Create<TSource, TKey>(Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }

    public static ProjectionEqualityComparer<TSource, TKey>
        Create<TSource, TKey> (TSource ignored,
                               Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }
}

public static class ProjectionEqualityComparer<TSource>
{
    public static ProjectionEqualityComparer<TSource, TKey>
        Create<TKey>(Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }
}

public class ProjectionEqualityComparer<TSource, TKey>
    : IEqualityComparer<TSource>
{
    readonly Func<TSource, TKey> projection;
    readonly IEqualityComparer<TKey> comparer;

    public ProjectionEqualityComparer(Func<TSource, TKey> projection)
        : this(projection, null)
    {
    }

    public ProjectionEqualityComparer(
        Func<TSource, TKey> projection,
        IEqualityComparer<TKey> comparer)
    {
        projection.ThrowIfNull("projection");
        this.comparer = comparer ?? EqualityComparer<TKey>.Default;
        this.projection = projection;
    }

    public bool Equals(TSource x, TSource y)
    {
        if (x == null && y == null)
        {
            return true;
        }
        if (x == null || y == null)
        {
            return false;
        }
        return comparer.Equals(projection(x), projection(y));
    }

    public int GetHashCode(TSource obj)
    {
        if (obj == null)
        {
            throw new ArgumentNullException("obj");
        }
        return comparer.GetHashCode(projection(obj));
    }
}
Run Code Online (Sandbox Code Playgroud)

二解决方案

要为Distinct执行此操作,您可以DistinctByMoreLINQ中使用扩展名:

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

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>
        (this IEnumerable<TSource> source,
         Func<TSource, TKey> keySelector,
         IEqualityComparer<TKey> comparer)
    {
        source.ThrowIfNull("source");
        keySelector.ThrowIfNull("keySelector");
        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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,ThrowIfNull看起来像这样:

public static void ThrowIfNull<T>(this T data, string name) where T : class
{
    if (data == null)
    {
        throw new ArgumentNullException(name);
    }
}
Run Code Online (Sandbox Code Playgroud)


kvb*_*kvb 6

在Charlie Flowers的答案的基础上,您可以创建自己的扩展方法来执行想要的操作,该方法内部使用分组:

    public static IEnumerable<T> Distinct<T, U>(
        this IEnumerable<T> seq, Func<T, U> getKey)
    {
        return
            from item in seq
            group item by getKey(item) into gp
            select gp.First();
    }
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个从EqualityComparer派生的通用类,但是听起来您想避免这种情况:

    public class KeyEqualityComparer<T,U> : IEqualityComparer<T>
    {
        private Func<T,U> GetKey { get; set; }

        public KeyEqualityComparer(Func<T,U> getKey) {
            GetKey = getKey;
        }

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

        public int GetHashCode(T obj)
        {
            return GetKey(obj).GetHashCode();
        }
    }
Run Code Online (Sandbox Code Playgroud)


Sim*_*ver 5

这是我能想出的最好的解决问题的方法。仍然很好奇是否有一种很好的方法可以EqualityComparer即时创建一个。

Galleries.SelectMany(x => x.Images).ToLookup(x => x.id).Select(x => x.First());
Run Code Online (Sandbox Code Playgroud)

创建查找表并从每个表中取出“顶部”

注意:这与@charlie 建议的相同,但使用 ILookup - 我认为无论如何这是一个组必须的。