我有两个相同类型的列表,模型如下:
public string Id {get; set;}
public string Name {get; set;}
public string Value {get; set;}
第一个列表 - ListA是需要复制到第二个列表的内容 - 我们找到Id匹配的ListB
我已经实现了一个只检查Id的Comparer,然后做一个cross来查找重复项。
public bool Equals(Model x, Model y)
{
//Check whether the objects are the same object.
if (Object.ReferenceEquals(x, y)) return true;
return x != null && y != null && x.Id.Equals(y.Id);
}
public int GetHashCode(Model obj)
{
//Get hash code for the Name field if it is not null.
int hashProductName = obj.Id == null ? 0 : obj.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName;
}
现在做交叉:
IEnumerable<Model> duplicates = listA.Choices.Intersect(listB.Choices, new ModelComparer());
我想知道这是正确的方法吗?
答案 0 :(得分:2)
有两种主要方法可以做到这一点。我会做listB left join listA
。然后,您可以处理已连接的集并返回itemFromA ?? itemFromB
。这很干净。
另一种方法是首先使用listA.Intersect(listB)
计算交叉点。参数的顺序很重要,因此来自listA
的元素具有优先权(记录在案)。
然后你可以intersectionResult.Union(listB)
。由于listB
是交集的超集,因此返回listB
但intersectionResult
中的元素优先。
我认为这种方法很差,因为很难得出结论是正确的。加入方法很简单。
连接方法还允许您丢弃自定义比较器,这是一个麻烦。