How to use linq `Except` with multiple properties with different class?
You have said that you need only these objects from testListA
:
- there is not matching
ProductID
intestListB
- there is existing mathing
ProductID
, but with differentCategory
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<TestA>
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<TestA>
{
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<T>
to compare values.:
var result = testListA.Except(secondListA, new MyComparer ()).ToList();