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!

Filed under: , , , , ,

Comments

# Lambda Expressions: An Introduction

Sunday, October 11, 2009 5:46 PM by Deborah's Developer MindScape

My presentation at our local Code Camp was fun. I covered a lot of material and had a GREAT audience

Leave a Comment

(required) 
(required) 
(optional)
(required)