7

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;
    .
    .
    .
    .
}
Chris Hammond
  • 2,064
  • 5
  • 27
  • 53
  • Four upvotes in two minutes? For this to be a _good_ question, it requires to be a bit more informative: what have you tried (searching the web), what does this code do? – CodeCaster Nov 29 '13 at 14:41

1 Answers1

12

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?

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Yep, that's the one.... I had tried IEnumerble and IEnumerator interfaces, but not IEnumerble As for the "why not derive from List", I never thought to do that... Two lessons learnt in one day ... Thanks Jon – Chris Hammond Nov 29 '13 at 14:47
  • @Jon... Further to the "Derive from List" - I was trying to get this working and then came across this http://stackoverflow.com/questions/5376203/inherit-listt ... Apparently, deriving from List is not advised, so have switched to Collection – Chris Hammond Dec 02 '13 at 07:35
  • @ChrisHammond: Thanks, noted for future reference. – Jon Dec 02 '13 at 09:10