我有两个列表,如下所示.....结果返回为空

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类中重写GetHashCodePay方法,否则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/

10-11 18:23