Monday, June 7, 2010

Silverlight How To: Convert List to ObservableCollection

I was recently working on a Silverlight project where the service operations returned list of business object and the properties on ViewModel were observable collection. As there was no choice than to loop through items in the list and add them to observable collection, I came up with this generic extension method to alleviate the monotony.

   1:  /// <summary>
   2:  /// Converts a collection to specified collection. For instance, List to ObservableCollection.
   3:  /// </summary>
   4:  /// <typeparam name="T">Type of elements in the collection.</typeparam>
   5:  /// <typeparam name="TCollection">Collection that contains elements from the input sequence.</typeparam>
   6:  /// <param name="collection">Collection to convert from.</param>
   7:  /// <returns>TCollection</returns>
   8:  public static TCollection ToCollection<T, TCollection>(this IEnumerable<T> collection)
   9:      where TCollection : ICollection<T>, new()
  10:  {
  11:      var col = new TCollection();
  12:   
  13:      foreach (var item in collection)
  14:      {
  15:          col.Add(item);
  16:      }
  17:   
  18:      return col;
  19:  }

Because I had to convert to more than one type, for instance SortableObservableCollection<T>, ObservableCollection<T> I decided for a generic implementation.

No comments: