C# Language Language Integrated Queries (LINQ)


Example

//Example 1
int[] array = { 1, 5, 2, 10, 7 };

// Select squares of all odd numbers in the array sorted in descending order
IEnumerable<int> query = from x in array
                         where x % 2 == 1
                         orderby x descending
                         select x * x;
// Result: 49, 25, 1

Example from wikipedia article on C# 3.0, LINQ sub-section

Example 1 uses query syntax which was designed to look similar to SQL queries.

//Example 2
IEnumerable<int> query = array.Where(x => x % 2 == 1)
    .OrderByDescending(x => x)
    .Select(x => x * x);
// Result: 49, 25, 1 using 'array' as defined in previous example

Example from wikipedia article on C# 3.0, LINQ sub-section

Example 2 uses method syntax to achieve the same outcome as example 1.

It is important to note that, in C#, LINQ query syntax is syntactic sugar for LINQ method syntax. The compiler translates the queries into method calls at compile time. Some queries have to be expressed in method syntax. From MSDN - "For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition."