Dissecting a Lambda Expression

Intertech Tutorials

Dissecting a Lambda Expression

A C# lambda expression consists of two aspects, separated by the lambda operator (=>). To the left of the lambda operator is a set of arguments to process. If the lambda involves a single argument, it can optionally be wrapped in parentheses. To the right of the lambda operator is a set of code statements that process the arguments in question.


// C#
// Take the argument named 'i' and
// pass it to the statement (i % 2) == 0.
var evenNumbers = list.FindAll(i => (i % 2) == 0);

// You can optionally wrap a single arg in ().
var evenNumbers = list.FindAll((i) => (i % 2) == 0);

In VB, lambda expressions consist of the Function statement, which also has two aspects. The item wrapped in parentheses after the Function statement is the set of arguments to process. Unlike C#, VB lambda arguments must be wrapped in parentheses. After the argument set is the (single) code statement that will process the arguments.


' Take the argument named 'i' and
' pass it to the statement (i Mod 2) = 0.
Dim evenNumbers = list.FindAll(Function(i) (i Mod 2) = 0)

' This would be an error! You must wrap args in ().
Dim evenNumbers = list.FindAll(Function i (i Mod 2) = 0) ' Error!!

In this case, the ‘argument to process’ is simply named ‘i’. The ‘statements to process them’ is the same code logic you previously placed in the method called by the delegate target. And again, the lambda operator (=> / Function) is nothing more than a shorthand notation for manually creating a delegate type.

Be aware that the name of the argument can be anything you desire. Arguments processed by a lambda expression can be understood as ‘normal’ parameters sent into a ‘normal’ function. As you already know, when defining a function, you can name your parameters anything you wish. For example, consider the following update:


// C#
var evenNumbers =
list.FindAll(itemToProcess => (itemToProcess % 2) == 0);



' VB
Dim evenNumbers = list.FindAll(Function(itemToProcess) (itemToProcess Mod 2) = 0)

Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.