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
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);
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With