Add elements from IList to ObservableCollection

Viewed 43245

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 ObservableCollection<Bar> obs = new ObservableCollection<Bar>(); 
public void Foo(IList<Bar> list)
{
    obs = new ObservableCollection<Bar>(list); 
}

But how can I actually take the content of the IList and add it to my existing ObservableCollection? Do I have to loop over all elements, or is there a better way?

public void Foo(IList<Bar> list)
{
   foreach (var elm in list)
       obs.Add(elm); 
}
6 Answers

But how can I actually take the content of the IList and add it to my existing ObservableCollection? Do I have to loop over all elements, or is there a better way?

While there may be some "better" way which would involve using third party dependencies, some low level manipulation, etc. Simply looping over the collection is fine and works. I recommend doing that. In short—no, there is, effectively, no "better" way.


This is the old version of this answer, which is a misuse of LINQ (potentially iterating the collection twice just to save a line or two of code). I wanted to delete the answer entirely, but I can't, since it's the accepted answer.

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

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

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

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.

Related