Add elements from IList to ObservableCollection

后端 未结 6 1564
臣服心动
臣服心动 2020-12-25 12:23

I have an ObservableCollection, and I\'d like to set the content of an IList to this one. Now I could just create a new instance of the collection..:

public         


        
相关标签:
6条回答
  • 2020-12-25 13:08

    You could do

    public void Foo(IList<Bar> list)
    {
        list.ToList().ForEach(obs.Add);
    }
    

    or as an extension method,

        public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items)
        {
            items.ToList().ForEach(collection.Add);
        }    
    
    0 讨论(0)
  • 2020-12-25 13:08

    Here is an descendant to ObservableCollection<T> to add a message efficient AddRange, plus unit tests:

    ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

    0 讨论(0)
  • 2020-12-25 13:15

    If you do want to instantiate an observable collection and want to add a new range into Observable collection you can follow the following method I have tried:

    var list = new List<Utilities.T>();
                list.AddRange(order.ItemTransactions.ToShortTrans());
                list.AddRange(order.DealTransactions.ToShortTrans());
                ShortTransactions = new ObservableCollection<T>(list);
    

    in this way you can add the range into ObservableCollection without looping.

    0 讨论(0)
  • 2020-12-25 13:18

    Looping is the only way, since there is no AddRange equivalent for ObservableCollection.

    0 讨论(0)
  • 2020-12-25 13:21

    You could write your own extension method if you are using C#3+ to help you with that. This code has had some basic testing to ensure that it works:

    public static void AddRange<T>(this ObservableCollection<T> coll, IEnumerable<T> items)
    {
        foreach (var item in items)
        {
            coll.Add(item);
        }
    }
    
    0 讨论(0)
  • 2020-12-25 13:28

    There is a library that solves this problem. It contains an ObservableList that can wrap a List. It can be used in the following way:

    List<Bar> currentList = getMyList();
    var obvList = new ObservableList<Bar>(currentList);
    

    https://github.com/gsonnenf/Gstc.Collections.ObservableLists

    0 讨论(0)
提交回复
热议问题