Me Myself & C#

Manoj Garg’s Tech Bytes – What I learned Today

Archive for the ‘Delegates’ Category

Using Predicates with List.Find()

Posted by Manoj Garg on July 16, 2007

Yesterday, One of my team member had a requirement for searching a List for an object having a specific value for one of its member. After some googling I found out few links explaining use of Predicates for this kind of custom searching. It solved my purpose.. so here goes how I did it 🙂

For example, we have a class Employee with members like EmpCode, First Name , Last Name etc.

public class Employee{    
    //Private members for all the below described properties
    //Public Properties   
    public String EmpCode;    
    public String FirstName;    
    public String LastName;    
    public DateTime DateOfBirth;
    public String Department;
    public String Designation;
    //Methods

    //Constructor
    public Employee(String ecode, String fname, String lname, DateTime dob, String dept, String desg)
    {
         EmpCode = ecode;
         FirstName = fname;
         LastName = lname;
         DateOfBirth = dob;
         Department = dept;
         Designation = desg;    
    }
}
 
and we have a list of Employee objects..

public class EmployeeList : List<Employee>
{ }
 

Now suppose we have a list of employees and we want to search them on the basis of their first name. There are two ways to do it.

  1. we iterate through the complete list and compare each Employee object’s FirstName property to our required value
  2. Or, we can use predicates to search the intended objects.

Following code snippet shows how to use predicate in List.Find() method

EmployeeList elist = new EmployeeList();
elist.Add(new Employee("1","Mk","Garg",DateTime.Now,"ITG","Arch"));
elist.Add(new Employee("2","P","Jain",DateTime.Now,"SE","Engg"));
elist.Add(new Employee("3","A","Goyal",DateTime.Now,"QA","Lead"));
elist.Add(new Employee("4","Bob","Matt",DateTime.Now,"HR","Mgr"));

//Find Using Inline
Employee em = elist.Find(delegate(Employee e) { return e.FirstName == "Mk"; });

Here in the above code em will have the Employee object with FirstName = “Mk”

Output will be

Prdicate example output 

These predicates can be used as annonymous functions as we used in the above code function, or  we can define a function which accepts an Object of type, we want to search, as parameter, and it returns bool value indicating whether a record mathed the criteria specified. it is a static method.  For example, in our code suppose we want to search the employees by their designation we can do it like :

Employee edesg = elist.Find(FindByDesignation);

Here FindByDesignation is a method which looks like:

private static bool FindByDesignation(Employee e){return (e.Designation == “Lead”);}

Ha-P Coding 🙂

Posted in C#, Collections & Generics, Delegates | Tagged: , , , | 16 Comments »