There are a variety of extension methods defined in the .NET
Framework that uses Lambda Expressions. In the System.Core assembly, the
System.Linq namespace features two static classes containing a variety of
extensions for enumerable and queryable sources. Some of those expressions are
defined in the Where method, for example. The Where method is defined as
Listing 1
Where<TSource>(IEnumerable<TSource>, Func<TSource, bool>);
Note the second parameter; the Func (or function in VB.NET)
defines a lamdba expression. The generic parameters are the key. The first
parameter is the type that is being evaluated in the lambda expression, and the
second parameter is the value needing to be returned by the method. I'll get
to an example in a moment, but realize that the return type can be any value,
such as a string, double, business object, etc.
So how do we use Lambda expressions? In C#, the lambda
expression is defined as
Listing 2
var items = list.Where(I => I.FirstName == "Fred");
Let's step through this. First, the "=>" code
notes a lambda expression. The "I" parameter is the alias or name
for the object of type <TSource> as shown above in the Func statement.
The first parameter is the object being iterated through, or the item type of
the items in the collection. For instance, if you have a List<MyObject>,
"I" is a reference for the MyObject type. Therefore, in our
expression above, the result (which must be a boolean) only gets objects where
the first name is "Fred."
Everything to the right of the "=>" is defining
the criteria check for whether the method returns true and false. So how is it
used? Here is another example I created in my application. It works very
similar to a delegate, but is also a cross between delegates and anonymous
methods because the actual definition is on-the-fly. I actually wrote one for
an ASP.NET server control, which is the ListControl, because of its items
collection
Listing 3
public static IEnumerable < ListItem > FindItemsWith(this ListControl control,
Func < ListItem, bool > result)
{
List < ListItem > foundItems = new List < ListItem > ();
foreach (ListItem item in control.Items)
{
if (result(item))
foundItems.Add(item);
}
return foundItems;
}
Note the use of the lambda expression as declared as
Func<ListItem, bool>. The ListItem object is compared and the method
returns a boolean. In the looping below, each item in the list control is
iterated through. The lambda expression takes a reference to the ListItem
object and returns the boolean expression; if it evaluates to true, it is added
to the list, and the collection is returned to the caller.