我有一个基本的集合类,它只包含一个自定义对象的列表,保存在List变量中以允许我使用this []索引.
但是,我现在想要使类可以从集合 LINQ查询中的项运行
使用简化的类比,我可以通过刚刚从列表中获得一名工作人员
Employeex = MyStaffList[Payroll];
......但我现在想做的是
var HREmps = from emp in StaffList where emp.Department == "HR" select emp;
下面是原型类定义....
public class StaffList { Listlst = new List (); public StaffList() { /* Add Employees to the list */ } public Employee this[string payroll] { get { Employee oRet = null; foreach (Employee emp in lst) { if (emp.Payroll.Equals(payroll, StringComparison.InvariantCultureIgnoreCase)) { oRet = emp ; break; } } return (oRet); } } } public class Employee { public string Payroll; public string Department; . . . . }
Jon.. 12
您需要创建类实现IEnumerable
以启用LINQ.这很容易做到(只有一种方法,它可以return lst.GetEnumerator();
.
然而,更容易的是List
直接派生而不是派生object
.有没有理由你不这样做?
您需要创建类实现IEnumerable<Employee>
以启用LINQ.这很容易做到(只有一种方法,它可以return lst.GetEnumerator();
.
然而,更容易的是List<Employee>
直接派生而不是派生object
.有没有理由你不这样做?