C# Predicate

0

Category :

Predicate is a functional construct providing a convenient way of basically testing if something is true of a given T object.

The Predicate will always return a boolean, by definition.
Predicate is basically identical to Func
List of People objects and we need to find if one is named Oscar:

Old Method

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

if (oscar != null) {
    // Oscar exists!
}
If we need to find someone with a different name then we will need a lot more code using this method.

Predicate

Using Predicates involves much less code and maybe easier to read....maybe
Predicate oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate seventnYOFinder = (Person p) => { return p.Age == 17; };

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


my thanks to:
http://stackoverflow.com/questions/1710301/what-is-a-predicate-in-c

0 comments:

Post a Comment