IQueryable <a> to ObservableCollection <a>其中a =匿名类型

Ton*_*Nam 8 c# casting iqueryable observablecollection

我希望将listview的datacontext绑定到可观察的集合.现在我有:

               // 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;
Run Code Online (Sandbox Code Playgroud)

该代码正确填充列表视图.现在,每当我更新listview项时,我都想更新listview.

我希望变量q是ObservableCollection类型,而不必创建一个包含firstName,lastName,position等的自定义类...我该怎么做?

m-y*_*m-y 14

你可以欺骗并创建一个方法来为你做,因为方法可以自动推断泛型类型:

public ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> enumeration)
{
    return new ObservableCollection<T>(enumeration);
}
Run Code Online (Sandbox Code Playgroud)

哦,如果它有帮助你可以创建这个作为扩展方法,所以它更容易使用...由你决定.