Tuesday, May 13, 2008

How to Find an object in a generic List (Delegate sample)

In this lesson I am going to show you more examples about delegate. One of the best example of delegate could be Find method in generic list.
See this code:

public List personlist = new List();
private string searchName;
public void FillList()
personlist.Add(new Person("Alex", "Botco", 5));
personlist.Add(new Person("Tai", "Chang", 6));
personlist.Add(new Person("Ehsan", "Parsa", 9));
public Person FindPersonbyName(string name)
searchName = name;
return personlist.FindLast(new Predicate(this.CheckName));
private bool CheckName(Person p)
return p.Name == searchName;
public Person FindPersonById(int Id)
return personlist.FindLast(delegate(Person p) { return p.ID == Id; });

In this example as you see first in FillList Method some persons are added to personlist each person has name, family and Id. Now we want to search a person based on Id or name. VS 2005 for its generic list has some methods like Find, FindLast, ... these methods accept a delegate (an address of a method). The delegate definition is implemented by Microsoft which is like this:

public delegate bool Predict (T item);

in our example T is Person. Microsoft is using this delegate (which is a method you will write and assign to this delegate) to Find an Item in list. Since you are writing the logic of this method so you can compare whatever you need in the method assigned to delegate.

If you look at the FindPersonbyName method I created an object of delegate and then I addressed the checkName method. And in CheckName I compared names. The downside of this type of coding is that I had to keep name in another variable (searchName) then in check name I compared the person name with searchName.
Another way to write the code is using delegate keyword inside FindLast method you can see an example of this in FindPersonById in this method instead of creating method and then create an object of delegate an assign that method to delegate we are writing the whole implementation in one line.
The syntax always is like this first delegate keyword then imagine we are writing a method so next step is having a parameter again this parameter is always an instance of object that we have in list. In our example that object is Person. Then in {} we write the code as if we were writing inside a method again always we are using the instance we declared in parameter and then compare one of its properties with other variables. The good point about writing code like this is that we do not need to define extra field like searchName in last methd.

I am going to dedicate this article to my dear friend Jeff.


Unknown said...

A great article Emad. Thanks for your kind dedication and for all your help to understand these topics.

Nahid said...

I envy Jeff for his precious gift.

christepher25 said...

It is a great article