How to make an ObservableCollection clone?

Here's a way, as I understand it, just copies the links?

private ObservableCollection<Vm> _observable; public override void Execute(ObservableCollection<Vm> obs) { _observable = new ObservableCollection<Vm>(obs); } 
  • one
    And what exactly do you want? Deep copying so that the VM objects are copied too? Describe completely the desired effect. - VladD 2:01 pm
  • @VladD, yes, I need a deep copy. Inside a VM collection with object states, I need to replace them all with another state and for the UI to react to this. - Lightness
  • Okay, okay. How can an unhappy compiler guess how to clone a VM object? How does he know how to do it right? Do not offer a bit copy, it is almost always wrong. - VladD pm
  • @VladD has an idea when creating a clone to sort through the main collection, create a new Vm () {// state of objects} and add them to the new collection. - Lightness
  • Well, yes, so in theory it should be. But it is better to let the object itself deal with cloning, this is its competence. Wrote this in response. - VladD

1 answer 1

If you want deep cloning, your Vm class should be properly sloped. For example, it should provide the Clone function:

 class Vm { ... public Vm Clone() { return new Vm(...) { ... }; } } 

In this case, it is easy to clone:

 _observable = new ObservableCollection<Vm>(obs.Select(vm => vm.Clone())); 
  • Thank! You can also implement ICloneable. - Lightness
  • @Lightness: You can use ICloneable , but Clone returns an object , which is quite inconvenient. - VladD
  • @Lightness: Please! - VladD