Efficient way of updating a collection from anothe

2019-08-10 20:11发布

问题:

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.)