Making a custom class availabe to LINQ queries

c#, linq

Solution

You need to make your class implement `IEnumerable<Employee>` in order to enable LINQ. That's easy enough to do (there is only one method and it can just `return lst.GetEnumerator();`.

However, what is even easier is to derive from `List<Employee>` directly instead of deriving from `object`. Is there a reason you don't do that?

Problem

I have a basic collection class that simply wraps a list of a custom object, held in a List variable to allow me to use this[] indexing. However, I now want to make the class accessible for be able to run from item in collection LINQ queries Using a simplified analogy, I can get a staff member from the list by just doing ``` Employeex = MyStaffList[Payroll]; ``` ...but what I now want to do is ``` var HREmps = from emp in StaffList where emp.Department == "HR" select emp; ``` Below is proto-type class definition.... ``` public class StaffList { List<Employee> lst = new List<Employee>(); 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; . . . . } ```

Original source

Related problems