Intersect between two lists not working
You need to override the Equals
and GetHashCode
methods in your Pay
class, otherwise Intersect
doesn't know when 2 instances are considered equal. How could it guess that it is the EventId
that determines equality? oldPay
and newPay
are different instances, so by default they're not considered equal.
You can override the methods in Pay
like this:
public override int GetHashCode()
{
return this.EventId;
}
public override bool Equals(object other)
{
if (other is Pay)
return ((Pay)other).EventId == this.EventId;
return false;
}
Another option is to implement an IEqualityComparer<Pay>
and pass it as a parameter to Intersect
:
public class PayComparer : IEqualityComparer<Pay>
{
public bool Equals(Pay x, Pay y)
{
if (x == y) // same instance or both null
return true;
if (x == null || y == null) // either one is null but not both
return false;
return x.EventId == y.EventId;
}
public int GetHashCode(Pay pay)
{
return pay != null ? pay.EventId : 0;
}
}
...
var Result = nlist.Intersect(olist, new PayComparer());