如何得到两个列表的差值<>对象
本文关键字:对象 列表 两个 何得 | 更新日期: 2023-09-27 18:05:29
我生成一个名为Exceptions的Object列表:
public class Exceptions
{
public bool deleted { get; set; }
public DateTime OriginalDate { get; set; }
public DateTime StartUtc { get; set; }
public DateTime EndUtc { get; set; }
public Int32 NumParticipants { get; set; }
public String Subject { get; set; }
public String Location { get; set; }
}
列表A有2个对象,列表B有3个对象
我期待一个新的列表,它显示了两个对象之间的区别
我尝试了下面的函数:
var ListC = ListA.Except(ListB).ToList();
我在ListC中得到两个对象,它们看起来完全像ListA。但是我期望列表b中缺少的对象
我做错了什么?
Expect
使用一个默认的相等比较器来比较你的对象,它通过引用来比较它们。你需要实现一个自定义的相等比较器,并在Except方法中使用它。
如果你不知道如何为你的类型实现IEqualityComparer<T>
,你可以在MSDN上找到例子
您需要这样做:
var ListC = ListA.Except(ListB).Union(ListB.Except(ListA))
我建议您覆盖Equals()
和GetHashCode()
,以便您所期望的比较。
public class Exceptions
{
public override bool Equals(object o)
{
return this.Equals(o as Exceptions);
}
public bool Equals(Exceptions ex)
{
if(ex == null)
return false;
else
{
// Do comparison here
}
}
}
A Linq alternative,可能有一个更快的方法:HashSet.SymmetricExceptWith ():
var exceptions = new HashSet(listA);
exceptions.SymmetricExceptWith(listB);