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

前端 未结 8 1465
半阙折子戏
半阙折子戏 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:54

    Building on Charlie Flowers' answer, you can create your own extension method to do what you want which internally uses grouping:

        public static IEnumerable Distinct(
            this IEnumerable seq, Func getKey)
        {
            return
                from item in seq
                group item by getKey(item) into gp
                select gp.First();
        }
    

    You could also create a generic class deriving from EqualityComparer, but it sounds like you'd like to avoid this:

        public class KeyEqualityComparer : IEqualityComparer
        {
            private Func GetKey { get; set; }
    
            public KeyEqualityComparer(Func 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();
            }
        }
    

提交回复
热议问题