Condividi tramite


Standard Query Operators Overview

The standard query operators are the methods that form the Language-Integrated Query (LINQ) pattern. Most of these methods operate on sequences, where a sequence is an object whose type implements the IEnumerable<T> interface or the IQueryable<T> interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting and more.

There are two sets of LINQ standard query operators, one that operates on objects of type IEnumerable<T> and the other that operates on objects of type IQueryable<T>. The methods that make up each set are static members of the Enumerable and Queryable classes, respectively. They are defined as extension methods of the type that they operate on. This means that they can be called by using either static method syntax or instance method syntax.

In addition, several standard query operator methods operate on types other than those based on IEnumerable<T> or IQueryable<T>. The Enumerable type defines two such methods that both operate on objects of type IEnumerable. These methods, Cast<TResult>(IEnumerable) and OfType<TResult>(IEnumerable), let you enable a non-parameterized, or non-generic, collection to be queried in the LINQ pattern. They do this by creating a strongly-typed collection of objects. The Queryable class defines two similar methods, Cast<TResult>(IQueryable) and OfType<TResult>(IQueryable), that operate on objects of type Queryable.

The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (for example, Average and Sum) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object.

In the case of the methods that operate on in-memory collections, that is, those methods that extend IEnumerable<T>, the returned enumerable object captures the arguments that were passed to the method. When that object is enumerated, the logic of the query operator is employed and the query results are returned.

In contrast, methods that extend IQueryable<T> do not implement any querying behavior, but build an expression tree that represents the query to be performed. The query processing is handled by the source IQueryable<T> object.

Calls to query methods can be chained together in one query, which enables queries to become arbitrarily complex.

The following code example demonstrates how the standard query operators can be used to obtain information about a sequence.

Dim sentence = "the quick brown fox jumps over the lazy dog" 
        ' Split the string into individual words to create a collection. 
        Dim words = sentence.Split(" "c)

        Dim query = From word In words 
                    Group word.ToUpper() By word.Length Into gr = Group 
                    Order By Length _
                    Select Length, GroupedWords = gr

        Dim output As New System.Text.StringBuilder
        For Each obj In query
            output.AppendLine(String.Format("Words of length {0}:", obj.Length))
            For Each word As String In obj.GroupedWords
                output.AppendLine(word)
            Next 
        Next 

        'Display the output
        MsgBox(output.ToString())

        ' This code example produces the following output: 
        ' 
        ' Words of length 3: 
        ' THE 
        ' FOX 
        ' THE 
        ' DOG 
        ' Words of length 4: 
        ' OVER 
        ' LAZY 
        ' Words of length 5: 
        ' QUICK 
        ' BROWN 
        ' JUMPS 
string sentence = "the quick brown fox jumps over the lazy dog";
           // Split the string into individual words to create a collection. 
           string[] words = sentence.Split(' ');

           // Using query expression syntax. 
           var query = from word in words
                       group word.ToUpper() by word.Length into gr
                       orderby gr.Key
                       select new { Length = gr.Key, Words = gr };

           // Using method-based query syntax. 
           var query2 = words.
               GroupBy(w => w.Length, w => w.ToUpper()).
               Select(g => new { Length = g.Key, Words = g }).
               OrderBy(o => o.Length);

           foreach (var obj in query)
           {
               Console.WriteLine("Words of length {0}:", obj.Length);
               foreach (string word in obj.Words)
                   Console.WriteLine(word);
           }

           // This code example produces the following output: 
           // 
           // Words of length 3: 
           // THE 
           // FOX 
           // THE 
           // DOG 
           // Words of length 4: 
           // OVER 
           // LAZY 
           // Words of length 5: 
           // QUICK 
           // BROWN 
           // JUMPS 

Query Expression Syntax

Some of the more frequently used standard query operators have dedicated C# and Visual Basic language keyword syntax that enables them to be called as part of a query expression. For more information about standard query operators that have dedicated keywords and their corresponding syntaxes, see Query Expression Syntax for Standard Query Operators.

Extending the Standard Query Operators

You can augment the set of standard query operators by creating domain-specific methods that are appropriate for your target domain or technology. You can also replace the standard query operators with your own implementations that provide additional services such as remote evaluation, query translation, and optimization. See AsEnumerable<TSource> for an example.

The following links take you to topics that provide additional information about the various standard query operators based on functionality.

Sorting Data

Set Operations

Filtering Data

Quantifier Operations

Projection Operations

Partitioning Data

Join Operations

Grouping Data

Generation Operations

Equality Operations

Element Operations

Converting Data Types

Concatenation Operations

Aggregation Operations

See Also

Reference

Enumerable

Queryable

Extension Methods (C# Programming Guide)

Concepts

Introduction to LINQ Queries (C#)

Query Expression Syntax for Standard Query Operators

Classification of Standard Query Operators by Manner of Execution

Extension Methods (Visual Basic)