我有两个列表,见下文.....结果返回为空
List<Pay>olist = new List<Pay>();
List<Pay> nlist = new List<Pay>();
Pay oldpay = new Pay()
{
EventId = 1,
Number = 123,
Amount = 1
};
olist.Add(oldpay);
Pay newpay = new Pay ()
{
EventId = 1,
Number = 123,
Amount = 100
};
nlist.Add(newpay);
var Result = nlist.Intersect(olist);
有什么线索吗?
最佳答案
您需要覆盖 Equals
和 GetHashCode
Pay
中的方法类,否则 Intersect
不知道什么时候 2 个实例被认为是相等的。它怎么会猜到是EventId
呢?那决定平等? oldPay
和 newPay
是不同的实例,因此默认情况下它们不被视为相等。
您可以覆盖 Pay
中的方法像这样:
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;
}
另一种选择是实现 IEqualityComparer<Pay>
并将其作为参数传递给 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());
关于c# - 在两个列表之间相交不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8314707/