IQueryable <a> to ObservableCollection <a> where a = anonymous type

I want the datacontext of my list to be bound to an observable collection. Right now I have:

// CurrentEmploye = some employee Entities.DatabaseModel m = new Entities.DatabaseModel(); var q = from t in m.TimeSheet join emp in m.Employees on t.idEmployee equals emp.id where emp.id == CurrentEmploye.id select new { firstName = emp.firstName, lastName = emp.lastName, position = emp.position, clockInDate = t.clockInDate, clockOutDate = t.clockOutDate, }; listView1.DataContext = q; 

this code fills the list correctly. Now I want to update the list when I update the list item.

I would like the q variable to be of type ObservableCollection without creating my own class that contains firstName, lastName, position, etc. How can i do this?

+7
source share
2 answers

You can trick and create a method to do this for you, since methods can automatically call a generic type:

 public ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> enumeration) { return new ObservableCollection<T>(enumeration); } 

Oh, and if that helps, you can create this as an extension method to make it easier to use ... up to you.

+14
source

In addition to my answer, to use it as an extension, you must put "this" before the method argument:

 public ObservableCollection<T> ToObservableCollection<T>(this IEnumerable enumeration){ return new ObservableCollection<T>(enumeration) } 
+1
source

All Articles