I have a method in a Silverlight app that currently returns an IList and I would like to find the cleanest way to turn this into an ObservableCollection so:
public IList<SomeType> GetIlist()
{
//Process some stuff and return an IList<SomeType>;
}
public void ConsumeIlist()
{
//SomeCollection is defined in the class as an ObservableCollection
//Option 1
//Doesn't work - SomeCollection is NULL
SomeCollection = GetIlist() as ObservableCollection
//Option 2
//Works, but feels less clean than a variation of the above
IList<SomeType> myList = GetIlist
foreach (SomeType currentItem in myList)
{
SomeCollection.Add(currentEntry);
}
}
ObservableCollection doesn't have a constructor that will take an IList or IEnumerable as a parameter, so I can't simple new one up. Is there an alternative that looks more like option 1 that I'm missing, or am I just being too nit-picky here and option 2 really is a reasonable option.
Also, if option 2 is the only real option, is there a reason to use an IList over an IEnurerable if all I'm ever really going to do with it is iterate over the return value and add it to some other kind of collection?
Thanks in advance
In nutshell both List and ObservableCollection inherits ICollection, IList interfaces.
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.
Represents a dynamic data collection that provides notifications when items get added or removed, or when the whole list is refreshed.
You could write a quick and dirty extension method to make it easy
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable) {
var col = new ObservableCollection<T>();
foreach ( var cur in enumerable ) {
col.Add(cur);
}
return col;
}
Now you can just write
return GetIlist().ToObservableCollection();
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