How to use linq `Except` with multiple properties with different class?

后端 未结 3 1273
庸人自扰
庸人自扰 2020-12-16 06:11

I am trying to learn the Linq/Lambda expressions and was stuck at somewhere.

What I was Doing

I have created two classes with

3条回答
  •  孤街浪徒
    2020-12-16 06:32

    You have said that you need only these objects from testListA:

    • there is not matching ProductID in testListB
    • there is existing mathing ProductID, but with different Category

    So, your filter must be:

    !testListB.Any(b => a.ProductID == b.ProductID && a.Category == b.Category)

    So, change your code as:

    testListA.Where(a => !testListB.Any(b => a.ProductID == b.ProductID && a.Category == b.Category));
    

    Second approach:

    Or you can create a new List from the second list:

     var secondListA = testListB.Select(x=> new TestA(){Category=x.Category, ProductID=x.ProductID}).ToList();
    

    And then create your Comparer:

    sealed class MyComparer : IEqualityComparer
    {
        public bool Equals(TestA x, TestA y)
        {
            if (x == null)
                return y == null;
            else if (y == null)
                return false;
            else
                return x.ProductID == y.ProductID && x.Category == y.Category;
        }
    
        public int GetHashCode(TestA obj)
        {
            return obj.ProductID.GetHashCode();
        }
    }
    

    And use Except() overload which produces the set difference of two sequences by using the specified IEqualityComparer to compare values.:

    var result = testListA.Except(secondListA, new MyComparer ()).ToList();
    

提交回复
热议问题