Skip to content

C# Generics Find Method

David

Asked May 25, 2006, 11:32 AM EDT1 answer
Share
LinkedInX
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.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    The Delegate Equation
    List<someObj> listObj = new List<someObj>();
    someObj y1 = listObj.Filter(delegate (someObj x) { return x.someProperty == searchValue  || x.someotherproperty == 1234; })
    someObj y2 = listObj.Find(delegate (someObj x) { return x.someProperty == searchValue; })
    someObj y3 = listObj.FindLast(delegate (someObj x) { return x.someProperty == searchValue; })
    List<someObj> y4 = listObj.FindAll(delegate (someObj x) { return x.someProperty == searchValue; })
    bool bResult = listObj.RemoveAll(delegate (someObj x) { return x.someProperty == searchValue; })



    Example...

    public class MyName {

    public MyName(string fName, string lName) { FirstName = fName; LastName = lName; }

    public string FirstName = "";

    public string LastName = "";

    }

    //  In some window form button
    private void button1_Click(object sender, EventArgs e)

    {

    // This will find the MyName obj that firstname = "Sean"
    List<MyName> lstNames = new List<MyName>();

    lstNames.Add(new MyName("Sean", "Lanoue"));

    lstNames.Add(new MyName("Jack", "Lovejoy"));

    MyName xx = lstNames.Find(delegate(MyName x)

    { return x.FirstName =="Sean"; });

    MessageBox.Show(xx.LastName);

    }

    This also works for Filter, FindAll, Remove

    0