Lambda Expressions
Back in Chapter 17 we mentioned that lambda expressions were created for use with
LINQ, to create expressions that return a method instead of a single return value.
The same query we’ve been using all along could be written like this with lambda
expressions:
var resultsAuthor =
bookList.Where(bookEval => bookEval.Author == "Jesse Liberty");
As we mentioned in the previous section, the keyword var lets the compiler infer that
resultsAuthor is an IEnumerable collection. You can interpret this whole statement as
“fill the IEnumerable collection resultsAuthor from the collection bookList with each
member such that the Author property is equal to the string ‘Jesse Liberty’.”
The variable bookEval isn’t declared anywhere; it can be any valid name. The Boolean
expression on the righthand side is projected onto the variable, which is passed
to the Where method to use to evaluate the collection. This method syntax takes some
getting used to, and it can be easier to use LINQ’s query syntax, but you should
know how to use the alternative. This example is shown in Example 21-3.
Example 21-3. The LINQ method syntax uses lambda expressions to evaluate the data retrieved
from the data source:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lambda_Expressions
{
// simple book class
public class Book
{
...
}
class Program
{
static void Main(string[] args)
{
List
{
...
};
// find books by Jesse Liberty
var resultsAuthor =
bookList.Where(bookEval =>
bookEval.Author == "Jesse Liberty");
Console.WriteLine("Books by Jesse Liberty:");
foreach (var testBook in resultsAuthor)
{
Console.WriteLine("{0}, by {1}",
testBook.Title, testBook.Author);
}
}
}
}
No comments:
Post a Comment