Intersect LINQ query

后端 未结 7 1924
北恋
北恋 2020-11-30 00:57

If I have an IEnumerable where ClassA exposes an ID property of type long. Is it possible to use a Linq query to get all instances of ClassA with ID belonging to a second IE

相关标签:
7条回答
  • 2020-11-30 01:48

    I will post an answer using Intersect.

    This is useful if you want to intersect 2 IEnumerables of the same type.

    First we will need an EqualityComparer:

        public class KeyEqualityComparer<T> : IEqualityComparer<T>
        {
            private readonly Func<T, object> keyExtractor;
    
            public KeyEqualityComparer(Func<T, object> keyExtractor)
            {
                this.keyExtractor = keyExtractor;
            }
    
            public bool Equals(T x, T y)
            {
                return this.keyExtractor(x).Equals(this.keyExtractor(y));
            }
    
            public int GetHashCode(T obj)
            {
                return this.keyExtractor(obj).GetHashCode();
            }
        }
    

    Secondly we apply the KeyEqualityComparer to the Intersect function:

    var list3= list1.Intersect(list2, new KeyEqualityComparer<ClassToCompare>(s => s.Id));
    
    0 讨论(0)
提交回复
热议问题