The path to LINQ 5: a linq query expression

Source: Internet
Author: User
Document directory
  • Range variable
  • Query expression and method syntax
  • Combined query syntax

Another two types of Syntax are available when writing a LINQ Query: Method Syntax (Fluent Syntax) and Query Expression (Query Expression ).

The essence of the syntax of the LINQ method is to create a query through the extension method and Lambda expression. C #3.0 a declarative query expression, also called the query syntax, is introduced to a LINQ expression. Generally, it is a more convenient way to create a LINQ query. Although the query written by the query syntax is similar to the SQL query, the query expression is not created on the SQL, it is built on the list comprehensions function in functional programming languages such as LISP and Haskell. This article will introduce the syntax of the LINQ query in detail.

In the previous LINAQ method syntax, we used the following example to obtain all the names containing the letter "a", sort the names by length, and convert the results into uppercase letters. The following is the equivalent query expression syntax:

Static void Main (string [] args)
{
String [] names = {"Tom", "Dick", "Harry", "Mary", "Jay "};

IEnumerable <string> query =
From n in names
Where n. Contains ("a") // Filter elements
Orderby n. Length // Sort elements, (orderby n is changed to orderby n. Length. Thanks to the attacker for discovering this error)
Select n. ToUpper (); // Translate each element

Foreach (string name in query)
Console. WriteLine (name );
}

The query expression always starts with the from clause and ends with the select or group clause. The From clause defines the query range variable (range variable). It can be considered that this variable is a traversal of the input sequence, just as done by foreach. The following figure describes the complete syntax of the query expression:

Of course, the. NET public Language Runtime Library (CLR) does not have the concept of query syntax. During program compilation, the compiler converts the query expression to the method syntax, that is, calling the extension method. This means that all the LINQ queries written using the query expression have equivalent method syntax. For the query expression in the previous example, the compiler converts it to the following method Syntax:

            IEnumerable<string> query = names
.Where (n => n.Contains("a"))
.OrderBy(n => n.Length)
.Select (n => n.ToUpper());

Then, the application compiler will apply the processing rules for the method syntax. The above Where, OrderBy, and Select query operators will be bound to the corresponding extension methods in the Enumerable class.

Range variable

A range variable is a variable defined after the from keyword. A range variable points to the current element in the input sequence corresponding to the current operator. In our example, the range variable appears in each query clause, but note that the variable actually traverses different sequence, because Where, OrderBy, and Select have different input sequence:

IEnumerable <string> query =
From n in names // n is the defined range variable.
Where n. Contains ("a") // n is directly from the names array
Orderby n. Length // n comes from the subsequent after the filter
Select n. ToUpper (); // n comes from the subsequent after OrderBy

When the compiler translates the preceding query syntax into the method syntax, we will see more clearly the behavior of the range variable:

IEnumerable <string> query2 = names
. Where (n => n. Contains ("a") // n directly from names array
. OrderBy (n => n. Length) // n comes from the subsequent after the filter
. Select (n => n. ToUpper (); // n comes from subsequent after OrderBy

In addition to the range variable after the from keyword, the query expression also allows us to introduce a new range variable through the following clause:

  • Let
  • Into
  • Additional from clause

Later, we will discuss their usage methods and applicable scenarios in the "subquery, creation policy, and data conversion in LINQ" section.

Query expression and method syntax

The query expression and method syntax have their own advantages. In the following scenario, it is more concise to write a query expression:

  • Use the let keyword to introduce new range Variables
  • When an external range variable is referenced after selectscope, Join, or GroupJoin

When you simply use Where, OrderyBy, and Select, there is no big difference between the two syntax structures. In this case, you can choose any one based on your preferences.

For queries composed of only one query operator, the method syntax is shorter and easier to understand.

Finally, for query operators without corresponding query expression keywords, we can only select method syntax. The following operators have corresponding query expression keywords: Where, Select, SelectMany, OrderBy, ThenBy, OrderByDescending, ThenByDescending, GroupBy, Join, and GroupJoin.

Combined query syntax

When a query operator does not have the corresponding query syntax, we can combine the query syntax and method syntax. The only constraint is that the syntax of each query in the query must be complete. For example, the statement starts from and ends with select or group. For example:

String [] names = {"Tom", "Dick", "Harry", "Mary", "Jay "};

// Calculate the total number of names containing the letter ""
Int matches = (from n in names where n. Contains ("a") select n). Count (); // 3
// The first name in alphabetical order
String first = (from n in names orderby n select n). First (); // Dick

This combination syntax is usually advantageous in writing more complex queries. For simple queries like the above, we only need to use the method syntax to get good results:

             int matches = names.Where(n => n.Contains("a")).Count();    // 3
string first = (names.OrderBy(n => n)).First(); // Dick

 

Blog series Navigation:

Blog navigation of the road to LINQ

Road 1 of LINQ: Introduction to LINQ

The path to LINQ 2: C #3.0 language functions (I)

The path to LINQ 3: C #3.0 language functions (II)

The road to LINQ 4: the syntax of the LINQ Method

The path to LINQ 5: a linq query expression

6: latency in Execution (Deferred Execution)

7: subquery, creation policy, and Data Conversion

8: Explain query (Interpreted Queries)

Road 9: LINQ to SQL and Entity Framework (I)

10: The Path to LINQ to SQL and Entity Framework (below)

11: Filtering by LINQ Operators)

12: Data Conversion (Projecting) of LINQ Operators)

Connection to the LINQ road 13: connection to the LINQ Operators (Joining)

The road to LINQ 14: sorting and Grouping of LINQ Operators (Ordering and Grouping)

Road 15 to LINQ: Element Operators, set methods, and quantifiers of LINQ Operators

LINQ LINQ 16: Collection Operators, Zip Operators, conversion methods, and generator methods of LINQ Operators

X-DOM introduction to the road to LINQ 17: LINQ to XML;

18: navigation and query of LINQ to XML

Road 19: X-DOM update and interaction with Value attributes for LINQ to XML

Path 20 to LINQ to XML: Documents, Declarations, and Namespaces

The path to LINQ 21: The X-DOM for the generation of LINQ to XML (Projecting)

Post of the series of blogs on the road to LINQ

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.