两个列表之间相交不起作用

use*_*715 11 c# linq list

我有两个列表见下面.....结果回来是空的

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);
Run Code Online (Sandbox Code Playgroud)

任何线索为什么?

Tho*_*que 25

您需要覆盖类中的EqualsGetHashCode方法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;
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是实现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());
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以编写自己的比较器:http://msdn.microsoft.com/en-us/library/234b841s.aspx (2认同)