Lambda Expressions in LINQ
In Chapter 12, I mentioned that you can use lambda expressions to define inline delegate definitions. In the following expression:
customer => customer.FirstName == "Donna"
the left operand, customer, is the input parameter. The right operand is the lambda expression that checks whether the customer's FirstName property is equal to "Donna." Therefore, for a given customer object, you're checking whether its first name is Donna. This lambda expression is then passed into the Where method to perform this comparison operation on each customer in the customer list.
Queries defined using extension methods are called method-based queries. Although the query and method syntaxes are different, they are semantically identical, and the compiler translates them into the same IL code. You can use either of them based on your preference.
Let's start with a very simple query, as shown in Example 13-8.
Example 13-8. A simple method-based query
using System;
using System.Linq;
namespace SimpleLamda
{
class Program
{
static void Main(string[] args)
{
string[] names = { "Jesse", "Donald", "Douglas" };
var dNames = names.Where(n => n.StartsWith("D"));
foreach (string foundName in dNames)
{
Console.WriteLine("Found: " + foundName);
}
}
}
}
Output:
Found: Donald
Found: DouglasThe statement names.Where is shorthand for:
System.Linq.Enumerable.Where(names,n=>n.StartsWith("D"));Where is an extension method and so you can leave out the object (names) as the first argument, and by including ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access