Custom intersect in lambda

后端 未结 4 777
离开以前
离开以前 2021-02-08 01:37

I would like to know if this is possible to solve using a lambda expression:

List listOne = service.GetListOne();
List listTwo = service.Ge         


        
4条回答
  •  逝去的感伤
    2021-02-08 02:39

    Sure you can! You can use this overload of Linq's Intersect extension method which takes an IEqualityComparer, like this:

    public class FooComparer : IEqualityComparer 
    {
        public bool Equals(Foo x, Foo y)
        {
            return x.Id == y.Id && x.someKey != y.someKey;
        }
    
        public int GetHashCode(Foo x)
        {
            return x.Id.GetHashCode();
        }
    }
    
    ...
    
    var comparer = new FooComparer();
    List listOne = service.GetListOne();
    List listTwo = service.GetListTwo();
    List result = listOne.Intersect(listTwo, comparer).ToList();
    

提交回复
热议问题