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); }
In nutshell both List and ObservableCollection inherits ICollection, IList interfaces.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With