Chaining Query Operators

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<string> 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<string> filtered = names.Where(n => n.Contains("a"));
        IEnumerable<string> sorted = filtered.OrderBy(n => n.Length);
        IEnumerable<string> 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|
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.