Predicate Delegates

A predicate is a simple delegate that returns booleans
A predicate is a functional construct that provides a convenient way of testing is something is true or false
A predicate will always return a boolean.

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;

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);

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