Sunday 24 November 2019

c# - Making a custom class availabe to LINQ queries




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 lst = 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;
.
.
.
.
}

Answer



You need to make your class implement IEnumerable 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 directly instead of deriving from object. Is there a reason you don't do that?


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...