Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements from IList to ObservableCollection

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);  } 
like image 883
stiank81 Avatar asked Feb 02 '10 13:02

stiank81


People also ask

Is ObservableCollection an IList?

In nutshell both List and ObservableCollection inherits ICollection, IList interfaces.

What is ObservableCollection in WPF?

WPF ObservableCollection An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.


2 Answers

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);     }     
like image 168
Adam Ralph Avatar answered Oct 23 '22 09:10

Adam Ralph


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);     } } 
like image 27
RaYell Avatar answered Oct 23 '22 09:10

RaYell