How to copy observable collection
I have
Observablecollection<A> aRef = new Observablecollection<A>();
bRef = aRef();
In this case bot开发者_运维知识库h point to same ObservableCollection
. How do I make a different copy?
Do this:
// aRef being an Observablecollection
Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef);
This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method.
UPDATE
If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list:
List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere();
Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);
You could implement ICloneable
interface in you entity definition and then make a copy of the ObservableCollection
with a internal cast. As a result you will have a cloned List
without any reference to old items. Then you could create your new ObservableCollection
whit the cloned List
public class YourEntity : ICloneable {
public AnyType Property { get; set; }
....
public object Clone()
{
return MemberwiseClone();
}
}
The implementation would be
var clonedList = originalObservableCollection.Select(objEntity => (YourEntity) objEntity.Clone()).ToList();
ObservableCollection<YourEntity> clonedCollection = new ObservableCollection<YourEntity>(clonedList);
精彩评论