Cast LINQ result to ObservableCollection
Jon Skeet 在这个问题上给出了很好的答案,但我还是不能自己做。
classes 还是新手| , 所以我还在和他们一起学习阶段。
我制作了一个 LINQ to SQL 类,显然有很多自动生成的代码。这是添加类时生成的类的片段,与此问题相关。这显然链接到名为 Staff_Time_TBL
的数据库表。
public partial class Staff_Time_TBL : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _ID;
private System.Nullable<System.DateTime> _Date_Data;
}
我有一个我制作的工作类,它可以将我需要的数据获取到数据网格中, 它从两个日期之间以及从具有唯一员工编号的员工中提取数据。这样可以正常工作,但是当直接更新数据到数据库时,界面中的数据没有更新,see this question.
internal class DatabaseQueries
{
public static IEnumerable<Staff_Time_TBL> MainTable(DatabaseDataContext database, DateTime fromDate, DateTime toDate, int employeeNumber)
{
return database.Staff_Time_TBLs.Where(staff =>
staff.Date_Data > fromDate &&
staff.Date_Data < toDate &&
staff.Staff_No == employeeNumber);
}
This code in this answer是可以理解的,但我不知道 foo
需要是什么?
var linqResults = foos.Where(f => f.Name == "Widget");
var observable = new ObservableCollection<Foo>(linqResults);
如何创建一个 Observablecollection 类来保存 LINQ 查询?
这是我尝试做的事情,但在查询时给我一个编译错误。
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.ObjectModel.ObservableCollection'
public ObservableCollection<Staff_Time_TBL> observerableInfoData { get; set; }
public MainWindow()
{
DataContext = this; // required for C# binding
InitializeComponent();
observerableInfoData = new ObservableCollection<Staff_Time_TBL>();
observerableInfoData = sql.Staff_Time_TBLs.Where(staff => staff.Staff_No == SelectedEmployee.Key &&
staff.Date_Data == filterFrom &&
staff.Date_Data == filterTo).Select(staff => staff.Info_Data).ToList();
最佳答案
基本上,你需要通过 IEnumerable<Staff_Time_TBL>
实际查询到数据库的结果以初始化 ObservableCollection<Staff_Time_TBL>
:
var linqResults = sql.Staff_Time_TBLs
.Where(staff => staff.Staff_No == SelectedEmployee.Key &&
staff.Date_Data == filterFrom &&
staff.Date_Data == filterTo);
var observable = new ObservableCollection<Staff_Time_TBL>(linqResults);
关于c# - LINQ 查询到 ObservableCollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277807/