List.Find Method in C#.NET

30-05-2012

The List.Find method requires a delegate function which can compare an
object of the same type of the list and return if the object matches the
target object.

You can either declare a delegate separately or use following easy shortcut.

Following example populates a list of people and then finds for a particular
entry in the list:

Public Class Person
{
   Private String Name;
   Private int Age;

   Public Person(String Name)
   {
      this.Name = Name;
   }
}

Class Program
{
      public static void Main(String[] args)
      {
         List patients = new List();
         Person P1 = new Person("John");
         Person P2 = new Person("Ron");
         Person P3 = new Person("Martin");
         patients.Add(P1);
         patients.Add(P2);
         patients.Add(P3);

         // find Ron from the list
         Person resultingPatient = patients.Find(delegate(Person p) {
                               p.Name == "Ron"; });

         Console.WriteLine("Name of the patient found : " +
resultingPatient.Name);   // Will print " Name of the patient found : Ron"

      }
}

You can use the same method to implement a method which will do the search
for you as described below;


public Person FindPatient(String TargetName)
{
    Person P = patients.Find(delegate p) { return p == TargetName; });
    return P;
}

Menol

ILT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: