David

David

  • NA
  • 5
  • 0

C# Generics Find Method

May 25 2006 3:32 PM
Like many people, I have been having some trouble with the new Find method for the C# 2.0 generic classes.  My problem is perhaps best explained with an example.

Say you have a class Person, and a person has a Name.

If you had a List<Person> and you wanted to find users with short names, you could do something like this:


private void PrintShortNames
{
  List<Person> personList = new List<Person>();

  personList.add(new Person("David"));
  personList.add(new Person("Bob"));
  personList.add(new Person("Sue"));
  personList.add(new Person("Samantha"));

  List<Person> shortNames = personList.FindAll(new Predicate<Person>(IsShortName));

  foreach (Person p in shortNames)
  {
    Console.WriteLine(p.Name + " has a short name.");
  }
}

private bool IsShortName(Person p)
{
  if (p.Name.Length < 5)
    return true;
  else
    return false;
}

Okay.  That works fine.

But what if you wanted to search for a specific Person in the example above.  How would you go about doing that?  Since you have to use a delgate function to do the Find, and you can't pass a parameter to the function, how do you tell it what Person you are searching for?  Must you create a boolean function with the name you are searching for hard coded in it?  That does not seem practical.

Any help with this would be most apprecatied.

Answers (1)