Efficient way of updating a collection from another collection

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 07:28:21

问题


Is the following way of updating an ObservableCollection from another one (both based on the same class) good enough or it better to be done in another way (or just to be improved)?

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 is the primary key.
(Under good enough I mean fast and efficient).


回答1:


   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;

If myItem and c are different types, have a look at AutoMapper.




回答2:


As a complementary answer, you can use reflection to copy the N fields from one object to another. I've already talked about this here: How to refactor this? .

You can have your class (SomeClass) implement this code (both objects are the same class):

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

That way, if your class has new properties, you don't have to bother updating the code, it's already there!

For objects with different class, that's also doable via reflection by the property name, but there are some assumptions you have to make (what if property does not exist, what property is different type, what is property value is null, etc.)



来源:https://stackoverflow.com/questions/5747113/efficient-way-of-updating-a-collection-from-another-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!