.net 使用linq将一个列表的副本复制到另一个列表
我有两个相同类型和型号的列表,如下所示:.net 使用linq将一个列表的副本复制到另一个列表,.net,.net,我有两个相同类型和型号的列表,如下所示: public string Id {get; set;} public string Name {get; set;} public string Value {get; set;} 第一个list-ListA是需要复制到第二个list-ListB的内容,在这里我们发现Id匹配 我已经实现了一个比较器,它只检查Id,然后进行交集以查找重复项 public bool Equals(Model x, Model y) { /
public string Id {get; set;}
public string Name {get; set;}
public string Value {get; set;}
第一个list-ListA是需要复制到第二个list-ListB的内容,在这里我们发现Id匹配
我已经实现了一个比较器,它只检查Id,然后进行交集以查找重复项
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());
IEnumerable duplicates=listA.Choices.Intersect(listB.Choices,new ModelComparer());
我想知道这样做对吗?有两种主要方法。我会做
listB左加入listA
。然后,您可以处理联接集并返回itemFromA??itemFromB
。这很干净
另一种方法是首先使用listA.Intersect(listB)
计算交点。参数的顺序很重要,因此listA
中的元素具有优先权(这是有文档记录的)
然后可以执行intersectionResult.Union(listB)
。由于listB
是交集的超集,因此返回listB
,但以intersectionResult
中的元素为优先
我认为这种方法是低劣的,因为很难断定它是正确的。join方法很简单
联接方法还允许您扔掉自定义比较器,这是一个麻烦。您想确定两个集合共有哪些元素吗?列表中是否有重复项?我们需要的唯一公共元素是Id(Id将始终是唯一的);只要Id匹配,我们希望覆盖整个对象。可能存在这样的情况:ListA有3个对象,ListB只有1个。我们只需要找到1,然后从ListA中更新它。这是正确的吗?Join(listA.Choices,p=>p.Id,m=>m.Id,(a,m)=>new{m.Id,m.Name});你测试过了吗?这将丢弃列表中不常见的所有项目<代码>从b中的b加入a中的b上。。。等于。。。在j中,让a=j.SOD()选择b??a。看起来像一个神奇的咒语,但它结合了众所周知的模式,如左连接LINQ模式。