Relativity
Relativity

Reputation: 6868

How to copy observable collection

I have

Observablecollection<A> aRef = new Observablecollection<A>();
bRef = aRef(); 

In this case both point to same ObservableCollection. How do I make a different copy?

Upvotes: 23

Views: 45944

Answers (2)

Jaime Mar&#237;n
Jaime Mar&#237;n

Reputation: 598

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

Upvotes: 11

Aliostad
Aliostad

Reputation: 81660

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

Upvotes: 33

Related Questions