System.Predicate

Added in .NET 3.5
The Predicate delegate is a special case of a Func, in that it takes only a single parameter and always returns a bool.
A predicate is a simple delegate that always returns booleans
A predicate is a functional construct that provides a convenient way of testing is something is true or false

class Person { 
    public string Name { get; set; }
    public int Age { get; set; }
}

Lets suppose that we have a List<Person> and we want to know if anyone has the name "Peter"
You could accomplish this by looping through the code

Person oscar = null; 
foreach (Person person in people) {
    if (person.Name == "Oscar") {
        oscar = person;
        break;
    }
}

if (oscar != null) {
    // Oscar exists!
}

Lets suppose you also wanted to do some other tests, like is there anyone with the name "Steve"
or is there anyone with the age 35.
Using a Predicate will significantly reduce the amount of code you need to write

System.Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; }; 
System.Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
System.Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };

Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext