Extension Methods

If you already know a little SQL, the query expressions introduced in previous sections are quite intuitive and easy to understand because LINQ is similar to SQL. As C# code is ultimately executed by the .NET CLR, the C# compiler has to translate query expressions to the format understandable by .NET. Because the .NET runtime understands method calls that can be executed, the LINQ query expressions written in C# are translated into a series of method calls. Such methods are called extension methods, and they are defined in a slightly different way than normal methods.

Example 13-5 is identical to Example 13-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 13-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 13-1
    }

    // Main program
    public class Tester
    {
        static void Main(  )
        {
            List<Customer> customers = CreateCustomerList(  );

            // Find customer by first nameIEnumerable<Customer> result =
                customers.Where(customer => customer.FirstName == "Donna"); Console.WriteLine("FirstName == \"Donna\""); foreach (Customer customer in result) Console.WriteLine(customer.ToString( )); } // Create a customer list with sample data private static List<Customer> CreateCustomerList( ) { // Same as in Example 13-1 } } } Output: ...

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.