But that is true only of string's, right. If I had a List of
"person", an object of lastname, firstname, age, and so on, and I
wanted to find a person with the same last name only, I still need a
predicate. Or at least that is my understanding.
Assuming you have a class called Person which has various properties
(such as FirstName, and LastName). Let's create a few persons (the
constructor takes the first and last name), and add them to a list:
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Jane", "Doe");
Person p3 = new Person("Jane", "Smith");
List<Person> people = new List<Person> {p1, p2, p3};
// So now we have a list of three Person objects. Perhaps we want to
// find all of those who have "Doe" as the surname. You need to call
// the FindAll function on the list, providing a Predicate, which is a
// method with a particular signature.
List<Person> does = people.FindAll(findDoes);
// If "findDoes" is a predicate which takes a person and returns
// true if the person has the LastName equal to "Doe" then
// we should have a list of two items - John and Jane Doe.
// The predicate can be defined like this:
private static bool findDoes(Person person)
{
return (person.LastName == "Doe");
}
Now this is a bit awkward if you then want to find all the people
where FirstName equals "Jane". You have to define another predicate.
There are ways around this - you can create a class which takes the
parameter (what the first name should be) in the constructor and which
uses that when determining what to return in the predicate, but this
is a bit nasty.
Really the only thing you care about is the expression which describes
the items you want back, in this case:
person.LastName == "Doe"
So, we have anonymous delegates. You don't have to declare them, you
just use them inline. The line:
List<Person> does = people.FindAll(findDoes);
becomes:
List<Person> does = people.FindAll(delegate(Person person)
{
return person.LastName == "Doe";
});
// The delegate here is anonymous because it doesn't have a name
// (unlike "findDoes"). But it does the same thing, and if you need to
// search for FirstNames that equal "John", you can just alter it a
// bit:
List<Person> johns = people.FindAll(delegate(Person person)
{
return person.FirstName == "John";
});
// if you're using C# 3.0, there's an even more concise syntax
// available: the lambda expression:
List<Person> does3 = people.FindAll(person => person.LastName ==
"Doe");
HTH