views:

755

answers:

3

Hello,

I have a LINQ statement that returns an implicit type. I need to get this type to be an ObservableCollection in my Silverlight 3 application. The ObservableCollection constructor in Silverlight 3 only provides an empty constructor. Because of this, I cannot directly convert my results to an ObservableCollection. Here is my code:

ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
                      select visibleTask;

filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList();  // This throws a compile time error

How can I go from an implicitly typed variable to an observable collection?

Thank you

+3  A: 

You can add the items manually, like this:

visibleTasks = new ObservableCollection<MyTasks>();
foreach(var item in filteredResults)
    visibleTasks.Add(item);

You can do this in one line using the following extension method:

///<summary>Adds zero or more items to a collection.</summary>
public static void AddRange<TItem, TElement>(this ICollection<TElement> collection, IEnumerable<TItem> items)
    where TItem : TElement {
    if (collection == null) throw new ArgumentNullException("collection");
    if (items == null) throw new ArgumentNullException("items");

    foreach (var item in items)
        collection.Add(item);
}

visibleTasks = new ObservableCollection<MyTasks>();
visibleTasks.AddRange(filteredResults);
SLaks
+1  A: 

Use the ObservableCollection<T> constructor that takes an IEnumerable<T> :

ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
                      select visibleTask;

filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = new ObservableCollection<MyTasks>(filteredResults);  // This throws a compile time error
Thomas Levesque
This constructor is not available in Silverlight. http://msdn.microsoft.com/en-us/library/ms653201%28VS.95%29.aspx
SLaks
argh... it's because of that kind of things that I don't develop in Silverlight, it's *so* frustrating...
Thomas Levesque
+1  A: 

You can write an extension method that converts an enumeration to an ObservableCollection, like so:

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
{
  ObservableCollection<T> obsColl = new ObservableCollection<T>();
  foreach (T element in source)
  {
    obsColl.Add( element );
  }
  return obsColl;
}

Now you can call the following statement:

visibleTasks = filteredResults.ToObservableCollection();
GreenIcicle
To make this a valid extension method on IEnumerable the method params need to be defined as:public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
Aaron
Sorry, you're right, corrected.
GreenIcicle