All notes


MSDN: Linq.

LINQ: Language-Integrated Query. Introduced in the .NET Framework version 3.5.

You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. LINQ support is also provided by third parties for many Web services and other database implementations.

A query is executed in a foreach statement, and foreach requires IEnumerable or IEnumerable<T>. (wcfNote: A query returns IEnumerable.) Types that support IEnumerable<T> or a derived interface such as the generic IQueryable<T> are called queryable types.

Query from an array:

using System;
using System.Linq;

class IntroToLINQ
    static void Main()
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable<int>
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQuery)
            Console.Write("{0,1} ", num); // 0 2 4 6

Query from a MDF:

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

// Query for customers in London.
IQueryable<Customer> custQuery =
    from cust in db.Customers
    where cust.City == "London"
    select cust;

LINQ query variables are typed as IEnumerable<T> or a derived type such as IQueryable<T>. When you see a query variable that is typed as IEnumerable<Customer>, it just means that the query, when it is executed, will produce a sequence of zero or more Customer objects.