๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Query Syntax

Query syntax writes a LINQ query with clauses that read like a sentence. A query starts with from and ends with select.

A first query

The from clause walks the list. The where clause keeps numbers above 2 and select returns each one.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 4, 1, 7, 2, 6 };
        var query = from n in numbers
                    where n > 2
                    select n;
        foreach (int n in query)
        {
            Console.WriteLine(n);
        }
    }
}

Sorting with orderby

The orderby clause sorts the kept numbers. The result prints from the smallest value to the largest.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 4, 1, 7, 2 };
        var query = from n in numbers
                    orderby n
                    select n;
        foreach (int n in query)
        {
            Console.WriteLine(n);
        }
    }
}

A mixed form

A query can hand its result to a method call. Select doubles each number that the query kept.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 3, 1, 5, 2 };
        var filtered = from n in numbers
                       where n > 2
                       select n;
        var doubled = filtered.Select(n => n * 10);
        foreach (int n in doubled)
        {
            Console.WriteLine(n);
        }
    }
}

Example

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        List<int> values = new List<int> { 8, 3, 9, 4, 7 };
        var query = from v in values
                    where v > 4
                    orderby v descending
                    select v * 2;
        foreach (int n in query)
        {
            Console.WriteLine(n);
        }
    }
}

Key points

  • The from clause names one item and its source.
  • The where clause keeps the items that pass a test.
  • The select clause chooses the result for each kept item.
  • The orderby clause sorts the result inside the query.
  • The compiler rewrites query syntax into the same method calls.
  • A query result can feed a method call in a mixed form.

In this example, where keeps 8, 9 and 7. The orderby clause sorts those values from largest to smallest. Select doubles each one and the loop prints 18, 16 and 14.

Note

Query syntax and method syntax run the same way.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the compiler do with query syntax?