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
You could write a quick and dirty extension method to make it easy
Now you can just write