LINQ C# Book

To build more complex queries, you append query operators to the expression.
To illustrate, the following query extracts all strings containing the letter "a", sorts them by length, and then converts the results to uppercase:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string[] names = { "C", "Java", "C#", "Javascript" };
IEnumerable query = names
.Where(n => n.Contains("a"))
.OrderBy(n => n.Length)
.Select(n => n.ToUpper());
foreach (string name in query)
Console.WriteLine(name);
}
}

The output:
JAVA
JAVASCRIPT
n is scoped to each of the lambda expressions.
We can rewrite the query above in separate statement.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string[] names = { "C", "Java", "C#", "Javascript" };
IEnumerable filtered = names.Where(n => n.Contains("a"));
IEnumerable sorted = filtered.OrderBy(n => n.Length);
IEnumerable finalQuery = sorted.Select(n => n.ToUpper());
foreach (string name in filtered)
Console.Write(name + "|");
Console.WriteLine();
Console.WriteLine();
foreach (string name in sorted)
Console.Write(name + "|");
Console.WriteLine();
Console.WriteLine();
foreach (string name in finalQuery)
Console.Write(name + "|");
Console.WriteLine();
}
}
The output:
Java|Javascript|
Java|Javascript|
JAVA|JAVASCRIPT|