如果您想要一个想要相交的单个属性的列表,那么所有其他漂亮的 LINQ 解决方案都可以正常工作。但!如果您想在整个班级上相交并因此有 aList<ThisClass>
而不是List<string>
您必须编写自己的相等比较器。
foo.Intersect(bar, new YourEqualityComparer());
与 相同Except
。
public class YourEqualityComparer: IEqualityComparer<ThisClass>
{
#region IEqualityComparer<ThisClass> Members
public bool Equals(ThisClass x, ThisClass y)
{
//no null check here, you might want to do that, or correct that to compare just one part of your object
return x.a == y.a && x.b == y.b;
}
public int GetHashCode(ThisClass obj)
{
unchecked
{
var hash = 17;
//same here, if you only want to get a hashcode on a, remove the line with b
hash = hash * 23 + obj.a.GetHashCode();
hash = hash * 23 + obj.b.GetHashCode();
return hash;
}
}
#endregion
}