如何在 C# 中查找两个 Collections<T> 的差异
How to find Difference in two Collections<T> in C#
我有以下两个合集class
public class ABC
{
public int studentId {get;set;}
public int schoolId {get;set;}
// Class has other properties too both above two are the keys
}
现在我有两套ABC
ICollection<ABC> C1 = {Some Data}
ICollection<ABC> C2 = {Some Data}
我想根据键找到 C1 中不在 C2 中的 ABC 对象,即 StudentId 和 SchoolId
使用Except
var diff = C1.Except(C2)
另请注意,为了跟踪相等性,您可以重写 Equals 方法,或者实施 IEqualityComparer 并将其传递给 Except 方法
class ABCEqualityComparer : IEqualityComparer<ABC>
{
public bool Equals(ABC b1, ABC b2)
{
return (b1.studentId == b2.studentId) && (b1.schoolId == b2.schoolId)
}
public int GetHashCode(ABC b)
{
return 7*b.studentId.GetHashCode() + b.schoolId.GetHashCode();
}
}
你可以使用
var diff = C1.Except(C2, new ABCEqualityComparer())
我有以下两个合集class
public class ABC
{
public int studentId {get;set;}
public int schoolId {get;set;}
// Class has other properties too both above two are the keys
}
现在我有两套ABC
ICollection<ABC> C1 = {Some Data}
ICollection<ABC> C2 = {Some Data}
我想根据键找到 C1 中不在 C2 中的 ABC 对象,即 StudentId 和 SchoolId
使用Except
var diff = C1.Except(C2)
另请注意,为了跟踪相等性,您可以重写 Equals 方法,或者实施 IEqualityComparer 并将其传递给 Except 方法
class ABCEqualityComparer : IEqualityComparer<ABC>
{
public bool Equals(ABC b1, ABC b2)
{
return (b1.studentId == b2.studentId) && (b1.schoolId == b2.schoolId)
}
public int GetHashCode(ABC b)
{
return 7*b.studentId.GetHashCode() + b.schoolId.GetHashCode();
}
}
你可以使用
var diff = C1.Except(C2, new ABCEqualityComparer())