Copy ObservableCollection to another ObservableCol

2019-04-17 04:15发布

问题:

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?

回答1:

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


标签: c# mvvm