I have a LINQ statement that returns an anonymous type. I need to get this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it to a
List myObjects;
Can someone tell me how to do this?
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 a anonymous type to an observable collection?
Thank you
As Ekin suggests, you can write a generic method that turns any
IEnumerable<T>into anObservableCollection<T>. This has one significant advantage over creating a new instance ofObservableCollectionusing constructor – the C# compiler is able to infer the generic type parameter automatically when calling a method, so you don’t need to write the type of the elements. This allows you to create a collection of anonymous types, which wouldn’t be otherwise possible (e.g. when using a constructor).One improvement over Ekin’s version is to write the method as an extension method. Following the usual naming pattern (such as
ToListorToArray), we can call itToObservableCollection:Now you can create an observable collection containing anonymous types returned from a LINQ query like this: