Extension Methods
LINQ is similar to SQL, so if you already know a little SQL the query expressions introduced in the previous sections should seem quite intuitive and easy to understand. However, as C# code is ultimately executed by the .NET CLR, the C# compiler has to translate the query expressions to a format that the .NET runtime understands. In other words, the LINQ query expressions written in C# must be translated into a series of method calls. The methods called are known as extension methods, and they are defined in a slightly different way than normal methods.
Example 9-5 is identical to Example 9-1, except it uses query operator extension methods instead of query expressions. The parts of the code that have not changed are omitted for brevity.
Example 9-5. Using query operator extension methods
using System;
using System.Collections.Generic;
using System.Linq;
namespace Programming_CSharp
{
// Simple customer class
public class Customer
{
// Same as in Example 9-1
}
// Main program
public class Tester
{
static void Main()
{
List<Customer> customers = CreateCustomerList();
// Find customer by first name
IEnumerable<Customer> result =
customers.Where(
customer => customer.FirstName == "Donna");
Console.WriteLine("FirstName == \"Donna\"");
foreach (Customer customer in result)
Console.WriteLine(customer.ToString());
Console.Read();
}
// Create a customer list with sample data
private static List<Customer> CreateCustomerList()
{
// Same as in Example 9-1
}
}
}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