Add elements from IList to ObservableCollection

stiank81 picture stiank81 · Feb 2, 2010 · Viewed 37.1k times · Source

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

Answer

Adam Ralph picture Adam Ralph · Feb 2, 2010

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