从另一个集合更新集合的有效方法

时间:2011-04-21 16:38:22

标签: c# .net linq collections observablecollection

以下更新ObservableCollection来自另一个(基于同一个类)的方式是否足够好,还是以其他方式更好(或者只是需要改进)?

foreach (MyEntity c in collection2)
    {
       collection1.Where(p => p.EntID == c.EntID).FirstOrDefault().Field1 = c.Field1;
       collection1.Where(p => p.EntID == c.EntID).FirstOrDefault().Field2 = c.Field2;
       ...
       collection1.Where(p => p.EntID == c.EntID).FirstOrDefault().FieldN = c.FieldN;         
    }

EntID是主键 (足够好,我的意思是快速有效)。

2 个答案:

答案 0 :(得分:3)

   var myItem = collection1.Where(p => p.EntID == c.EntID).FirstOrDefault();
   if (myItem == null)
       continue;
   myItem.Field1 = c.Field1;
   myItem.Field2 = c.Field2;
   ...
   myItem.FieldN = c.FieldN;

如果myItemc是不同的类型,请查看AutoMapper。

答案 1 :(得分:2)

作为补充答案,您可以使用反射将N个字段从一个对象复制到另一个对象。我已在这里谈过这个问题:How to refactor this?

您可以让您的类(SomeClass)实现此代码(两个对象都是同一个类):

public void CopyPropertiesFrom(SomeClass SourceInstance)
{
    foreach (PropertyInfo prop in typeof(SomeClass).GetProperties())
        prop.SetValue(this, prop.GetValue(SourceInstance, null), null);
}

这样,如果你的类有新的属性,你不必费心更新代码,它已经存在了!

对于具有不同类的对象,这也可以通过属性名称的反射来实现,但是您必须做出一些假设(如果属性不存在,什么属性是不同的类型,什么是属性值为null,等等) 。)

相关问题