Saturday, April 05, 2008

Generic List Predicates

Have you ever considered of searching on a list based upon a single value, for example we have a List and Employee contains a Property names Name and EmpCode.

There are many ways to search for it, we can walk through a foreach loop, or call our database, or whatsoever But we also have functions called Find and FindAll that expects a function the returns a bool value.

Now how we can use it. Suppose we are having a list of Employees say :

List lstEmployee

and we want to search an employee that contains EmpCode = 0.

We can write a function like:

int _empCode = 4;

Employee empWithCode = lstEmployee.FindAll(new Predicate(GetSingleEmployeeForCode));

private void GetSingleEmployeeForCode(Employee emp)

{

if (emp.EmpCode == _empCode)

    {

    return true;
    }

return false;

}

This will return us the employee with EmpCode 4.

Now how can we search for items that may have same value for different objects in list.

We have function like :

List maleEmpList;

maleEmpList = lstEmployee.FindAll(new Predicate(GetMaleEmployees));

private void GetMaleEmployees (Employee emp)

{

if (emp.Gender == "Male")

    {

    return true;
    }

return false;

}

No comments:

Post a Comment