Say you have a class Person, and a person has a Name.
If you had a List
private void PrintShortNames
{
List
personList.add(new Person("David"));
personList.add(new Person("Bob"));
personList.add(new Person("Sue"));
personList.add(new Person("Samantha"));
List
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.
Post CubPosted May 30, 2006, 10:12 PM
The Delegate Equation
ListsomeObj 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
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