Lambda Expressions: Predicate Delegates
Posted
Sun, Oct 11 2009 15:45
by
Deborah Kurata
According to Wikipedia, a predicate is “a function which returns a Boolean value”.
[To begin with an overview of lambda expressions, start here.]
A predicate delegate encapsulates a method that evaluates to True or False. It takes a single parameter.
The Array class Find method is an example of a predicate delegate. It takes an array as a first parameter and a predicate delegate as its second parameter.
In C#:
var foundCustomer = Array.Find(custArray, c =>
c.LastName.StartsWith("K"));
In VB:
Dim foundCustomer = Array.Find(custArray, Function(c) _
c.LastName.StartsWith("K"))
This code iterates through the array, checking each entry and evaluating the expression as true or false. If the expression is false, it continues. If the expression is true, it returns the entry. Basically, this code finds the first customer in the array with a last name that starts with the defined letter.
Enjoy!