I am trying to learn the Linq/Lambda expressions and was stuck at somewhere.
What I was Doing
I have created two classes with
You have said that you need only these objects from testListA:
ProductID in testListBProductID, but with different CategorySo, 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();