Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert Implict Type to ObservableCollection

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

like image 412
user70192 Avatar asked Feb 28 '10 15:02

user70192


3 Answers

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);
like image 64
SLaks Avatar answered Oct 02 '22 07:10

SLaks


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();
like image 24
GreenIcicle Avatar answered Oct 02 '22 06:10

GreenIcicle


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
like image 32
Thomas Levesque Avatar answered Oct 02 '22 06:10

Thomas Levesque