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

∥☆過路亽.° 提交于 2019-12-12 08:35:05

问题


I want the datacontext of my listview to be binded 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;

that code populates the listview correctly. Now I will like to update the listview whenever I update a listview item.

I will like the variable q to be of type ObservableCollection without having to create a custom class that holds firstName, lastName, position, etc... How can I do that?


回答1:


You can cheat and create a method to do it for you since methods can infer the generic type automatically:

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

Oh, and if it helps you can create this as an extension method so it's easier to use... up to you.




回答2:


In addition to m-y answer, in order to use it as an extension you should put "this" before the method argument:

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


来源:https://stackoverflow.com/questions/9984594/iqueryablea-to-observablecollectiona-where-a-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!