C # - convert anonymous type to observable collection

I have a LINQ statement that returns an anonymous type. I need this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it

List of 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 switch from an anonymous type to an observable collection?

thanks

+6
c # linq anonymous-types observablecollection
source share
5 answers

As Ekin says, you can write a generic method that turns any IEnumerable<T> into an ObservableCollection<T> . This has one significant advantage over creating a new instance of ObservableCollection using the constructor - the C # compiler is able to automatically call the type parameter when the method is called, so you do not need to write the element type. This allows you to create a collection of anonymous types, which would be impossible (for example, when using the constructor).

One improvement over the Ekin version is to write the method as an extension method. Following the usual naming scheme (e.g. ToList or ToArray ), we can call it ToObservableCollection :

 static ObservableCollection<T> ToObservableCollection<T> (this IEnumerable<T> en) { return new ObservableCollection<T>(en); } 

Now you can create an observable collection containing anonymous types returned from the LINQ query, for example:

 var oc = (from t in visibleTasks where t.IsSomething == true select new { Name = t.TaskName, Whatever = t.Foo } ).ToObservableCollection(); 
+6
source share

Something like this will do the job using type inference functions:

 private static ObservableCollection<T> CreateObservable<T>(IEnumerable<T> enumerable) { return new ObservableCollection<T>(enumerable); } static void Main(string[] args) { var oc = CreateObservable(args.Where(s => s.Length == 5)); } 
+2
source share

You should just do this:

 visibleTasks = new ObservableCollection<MyTasks>(filteredResults); 
+1
source share

Are you sure your object is indeed an ObservableCollection ? If so, you can simply click: visibleTasks = (ObservableCollection)filteredResults;

0
source share

Try:

 var filteredResults = from visibleTask in visibleTasks where(p => p.DueDate == DateTime.Today) select visibleTask).ToList(); 

(filtered results will contain the list you need)

0
source share

All Articles