我有一个类:
class ThisClass
{
private string a {get; set;}
private string b {get; set;}
}
我想使用 Linq 的 Intersect 和 Except 方法,即:
private List<ThisClass> foo = new List<ThisClass>();
private List<ThisClass> bar = new List<ThisClass>();
然后我分别填写两个列表。例如,我想执行以下操作(我知道这是不对的,只是伪代码):
foo[a].Intersect(bar[a]);
我该怎么做?
最佳答案
如果您想要一个要相交的单个属性的列表,那么所有其他漂亮的 LINQ 解决方案都可以正常工作。
但!如果你想在整个类(class)上相交,结果有一个 List<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
}
关于C# Linq 与对象的一部分相交/除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633375/