Copy ObservableCollection to another ObservableCollection

前端 未结 1 1266
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 16:49

How to copy ObservableCollection item to another ObservableCollection without reference of first collection? Here ObservableCollection

相关标签:
1条回答
  • 2021-01-03 17:14

    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);
    }
    
    0 讨论(0)
提交回复
热议问题