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;

}

How to perform Sort operation in List Generic List

Today I am coming with a small but efficient code for performing Sort operation in List. I am not going to explain it in much details as the code is

self understandable.

List braList;

braList = _branManager.GetBranchList();

braList.Sort

(

delegate(Branch braA, Branch braB)

{

if (CompanySortDirection == SortDirection.Ascending)

{

return braA.BranchCode.CompareTo(braB.BranchCode);

}

else// if (CompanySortDirection == SortDirection.Descending)

{

return braB.BranchCode.CompareTo(braA.BranchCode);

}

}

);

Depending upon the Sort Direction the list get sorted.