1

How to copy ObservableCollection item to another ObservableCollection without reference of first collection? Here ObservableCollection item value changes affecting both collections.

Code

private ObservableCollection<RateModel> _AllMetalRate = new ObservableCollection<RateModel>();
private ObservableCollection<RateModel> _MetalRateOnDate = new ObservableCollection<RateModel>();

public ObservableCollection<RateModel> AllMetalRate
{
    get { return this._AllMetalRate; }
    set
    {
        this._AllMetalRate = value;
        NotifyPropertyChanged("MetalRate");
    }
}

public ObservableCollection<RateModel> MetalRateOnDate
{
    get { return this._MetalRateOnDate; }
    set
    {
        this._MetalRateOnDate = value;
        NotifyPropertyChanged("MetalRateOnDate");
    }
}

foreach (var item in MetalRateOnDate)
    AllMetalRate.Add(item);

What is causing this and how can I solve it?

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
Sam Alex
  • 442
  • 1
  • 6
  • 21

1 Answers1

9

You need to clone the object referenced by item before it's added to AllMetalRate, otherwise both ObservableCollections will have a reference to the same object. Implement the ICloneable interface on RateModel to return a new object, and call Clone before you call Add:

public class RateModel : ICloneable
{

    ...

    public object Clone()
    {
        // Create a new RateModel object here, copying across all the fields from this
        // instance. You must deep-copy (i.e. also clone) any arrays or other complex
        // objects that RateModel contains
    }

}

Clone before adding to AllMetalRate:

foreach (var item in MetalRateOnDate)
{
    var clone = (RateModel)item.Clone();
    AllMetalRate.Add(clone);
}
Chris Mantle
  • 6,595
  • 3
  • 34
  • 48