Can you create a simple 'EqualityComparer' using a lambda expression

前端 未结 8 1462
半阙折子戏
半阙折子戏 2020-12-13 18:20

Short question:

Is there a simple way in LINQ to objects to get a distinct list of objects from a list based on a key property on the objects.

8条回答
  •  無奈伤痛
    2020-12-13 18:59

    What about a throw away IEqualityComparer generic class?

    public class ThrowAwayEqualityComparer : IEqualityComparer
    {
      Func comparer;
    
      public ThrowAwayEqualityComparer(Func comparer)   
      {
        this.comparer = comparer;
      }
    
      public bool Equals(T a, T b)
      {
        return comparer(a, b);
      }
    
      public int GetHashCode(T a)
      {
        return a.GetHashCode();
      }
    }
    

    So now you can use Distinct with a custom comparer.

    var distinctImages = allImages.Distinct(
       new ThrowAwayEqualityComparer((a, b) => a.Key == b.Key));
    

    You might be able to get away with the , but I'm not sure if the compiler could infer the type (don't have access to it right now.)

    And in an additional extension method:

    public static class IEnumerableExtensions
    {
      public static IEnumerable Distinct(this IEnumerable @this, Func comparer)
      {
        return @this.Distinct(new ThrowAwayEqualityComparer(comparer);
      }
    
      private class ThrowAwayEqualityComparer...
    }
    

提交回复
热议问题