Distinct list of objects based on an arbitrary key in LINQ

前端 未结 5 1398
鱼传尺愫
鱼传尺愫 2020-12-05 05:43

I have some objects:

class Foo {
    public Guid id;
    public string description;
}

var list = new List();
list.Add(new Foo() { id = Guid.Empt         


        
5条回答
  •  温柔的废话
    2020-12-05 06:19

    A very elegant and intention revealing option is to define a new extension method on IEnumerable

    So you have:

    list = list.Distinct(foo => foo.id).ToList();
    

    And ...

        public static IEnumerable Distinct(this IEnumerable list, Func lookup) where TKey : struct {
            return list.Distinct(new StructEqualityComparer(lookup));
        }
    
    
        class StructEqualityComparer : IEqualityComparer where TKey : struct {
    
            Func lookup;
    
            public StructEqualityComparer(Func lookup) {
                this.lookup = lookup;
            }
    
            public bool Equals(T x, T y) {
                return lookup(x).Equals(lookup(y));
            }
    
            public int GetHashCode(T obj) {
                return lookup(obj).GetHashCode();
            }
        }
    

    A similar helper class can be built to compare objects. (It will need to do better null handling)

提交回复
热议问题