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

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

有什么线索吗?

最佳答案

您需要覆盖 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/

相关文章:

c# - 一旦被调用者超出范围 : safe practice?,.NET 事件回调

c# - 在其中一个属性中获取具有最大日期时间值的对象

java - 每个 android 的 ConcurrentModificationException

c# - 使用 WebClient 时如何强制执行 SSL?

c# - Visual Studio ADO .NET 无法连接到 mysql 数据库

c# - 类型 '' 不能用作泛型类型或方法 'T' 中的类型参数 ''。没有从 '' 到 '' 的隐式引用转换

c# - {"error":"Explicit construction of entity type ' ## #' in query is not allowed."}

list - Haskell 函数 (a -> [b]) -> [a -> b]

c++ - 列表::迭代器上的算术运算?

c# - 如何在单个 LINQ 中获得两个不同的聚合?