Further Exploration with LINQ - Page 4
       by Granville Barnett  |  24 September 2007

In the previous page, we wrapped our look at how LINQ and XML work. The final topic that I will cover in this page concerns lambda expressions. Read on to find out more!

Lambda Expressions
Many people find lambda expressions fairly hard to get to grips with, so we will take some time to create some basic lambda expressions and then replicate some queries of in-memory collections and relational data using lambda expressions. If you have ever done any functional programming before in a language such as Haskell or F# then you will be familiar with the syntax of lambda expressions – if you have no experience with either, then don’t worry. We will go through lambda expressions now with a series of practical examples.

The first thing to clear up is the basic structure of a lambda expression; this takes the form of args => expression. For the first example we will create a function that returns the square of any given integer argument:

Func<int, int> square = x => x * x;
Console.WriteLine(square(3));

In this example we create a lambda expression that takes one argument (x) of type int, and returns an int. To the left of the => token is our single argument, and to the right of the => token is our expression (x*x).

Let’s now apply what we have just learned to filtering an in-memory collection. Just as before, our lambda expression will take a single argument, but this time return a Boolean value determined by whether or not the argument satisfied the expression:

List<string> people = new List<string>(){ "Granville",
                                        "Rachel",
                                        "John",
                                        "Ross",
                                          "Monica" };
 
IEnumerable<string> expr = people.Where(x => x.Length > 4);
 
foreach (string person in expr) {
Console.WriteLine(person);
}

Here we pass in an inline lambda expression to the Where extension method, in this case the parameter is of type string and the expression returns true only if the string has a length of greater than four characters.

For our final example we will use a lambda expression to select only the AuthorName property of the Author entity instead of creating an anonymous type. First we show how we would do this returning an anonymous type:

BookShop db = new BookShop(_conn);
 
var authors = from a in db.Authors
              select new { a.AuthorName };
 
foreach (var author in authors) {
Console.WriteLine(author.AuthorName);
}

Next we perform the same operation using a lambda expression:

BookShop db = new BookShop(_conn);
 
IEnumerable<string> authors = db.Authors.Select(x => x.AuthorName);
 
foreach (string author in authors) {
Console.WriteLine(author);
}

I strongly recommend that you familiarize yourselves with lambda expressions as they are incredibly useful when using LINQ. At the time of writing lambda expressions look set to become the de facto standard, with anonymous delegates playing a more subdued role in the future C# 3.0 language.

Summary
The simplicity and flexibility of LINQ has been shown throughout this article – it truly provides developers with a consistent language to query several data stores via several methods. An important fact to remember is that LINQ is still in early CTP stages, so logically it will only get better! I encourage everyone to further explore what LINQ can do, and more importantly how it can make your life a lot easier.

If you have any questions, please contact me or post on the forums.

Granville Barnett
Explorations in Programming 

 

1 | 2 | 3 | 4




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.