Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList<T> to ObservableCollection<T>

Tags:

c#

silverlight

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

like image 680
Steve Brouillard Avatar asked Apr 08 '09 20:04

Steve Brouillard


People also ask

Is ObservableCollection an IList?

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

What is an 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.

What is Observable collection in xamarin?

Represents a dynamic data collection that provides notifications when items get added or removed, or when the whole list is refreshed.


1 Answers

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();
like image 185
JaredPar Avatar answered Sep 21 '22 20:09

JaredPar