gpt4 book ai didi

c# - 在两个列表之间相交不起作用

转载 作者:可可西里 更新时间:2023-11-01 08:55:22 25 4
gpt4 key购买 nike

我有两个列表,见下​​文.....结果返回为空

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);

有什么线索吗?

最佳答案

您需要覆盖 EqualsGetHashCode Pay 中的方法类,否则 Intersect不知道什么时候 2 个实例被认为是相等的。它怎么会猜到是EventId呢?那决定平等? oldPaynewPay是不同的实例,因此默认情况下它们不被视为相等。

您可以覆盖 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com