Read notes on the basics of LINQ-Chapter 3: LINQ component Blocks

Source: Internet
Author: User

3.1 extensions of. Net by LINQ

Sequence 3.2

3.2.1 ienumerable <t> Interface

The array objects all implement the ienumerable <t> interface. This ienumerable <t> is the core of LINQ!

3.2.3 delayed query execution

The LINQ query statement is very dependent on delayed job seeking. In the case of LINQ, we call it deferred query execution, or deferredquery evaluation ). This is one of the most important concepts in LINQ-if this feature is missing, the execution efficiency of LINQ will be greatly reduced.

One advantage of delayed query execution is that it saves resources. The main point is that, when we know that we need to iteratively access the query results, the data source to be operated by a query will be accessed. Assume that a query returns thousands of elements. If subsequent elements are no longer needed after processing the first element, these subsequent elements will not be loaded into the memory-because each element will be provided in order. If all elements are stored in an array or a list, which is the same as the traditional programming model, these elements are loaded into the memory even if they are not required in the program.

Another advantage of delayed query execution is that we can separate the definition and usage of queries in different places. We can even use a defined query multiple times as needed.

Reuse the query to get different results

Another important feature that needs to be understood is that we may get different results when accessing a query in the second iteration. The following code provides such an instance

using System;using System.Linq; static classQueryReuse{       static double Square(double n)       {              Console.WriteLine("ComputingSquare("+n+")...");              return Math.Pow(n,2);       }        public static void Main()       {              int[] numbers = {1,2,3};              var query = from n in numbers              select Square(n);               foreach(var n in query)                     Console.WriteLine(n);              for(inti=0;i<number.Length;i++)                     numbers[i]=numbers[i]+10;               Console.WriteLine("-Collection updated -");               foreach(var n in query)                     Console.WriteLine(n);       }}

In the above Code, after the first query is executed, we changed the data source operated by the query ---- add 10 to each item, and then start the second execution.

The result of the two executions is:

Computing square (1 )...

1

Computing square (2 )...

4

Computing square (3 )...

9

---- Collection updated ---

Computing square (11 )...

121

Computing square (12 )...

144

Computing square (13 )...

169

The query is executed again in the second iteration and new results are obtained.

The query is executed immediately.

We can see that delayed execution is the default query behavior. That is, the query starts only when data is requested. If we want the query to be executed immediately, we need to send a request explicitly.

For example, if you want to complete the preceding query before processing the query results. That is to say, the square method has been called for each value before printing.

The output when execution is not delayed is shown below:

Computing square (1 )...

Computing square (2 )...

Computing square (3 )...

1

4

9

We use the tolist method to execute the preceding execution immediately. The tolist method is another extension method defined in the system. LINQ. enumerable class:

Foreach (VAR n inquery. tolist ())

Console. writeline (N );

With such a simple modification, the behavior of the Code is dramatically changed.

The tolist method accesses each structure of the query sequentially and creates a list <double> object containing each result in the query. Now, the foreach loop will operate on a predefined set, and the square method will not be called again during the iteration process.

3.3 query Operators

Common Features of the extension method (including where, orderbydescending, and select:

Operations are performed on the enumerated collection objects; data processing in the form of pipelines is allowed; dependent on delayed execution;

3.3.2 standard query Operators

We can combine query operators to perform a complex operation on an enumerated data source. Some predefined query operators cover a wide range of operations. These query operators are called standard query operators.

Standard query operators grouped by operation types

 

Type query operator

Filter oftype and where

Projection select, selectmany

Partition skip skipwhile take takewhile

Join groupjoin and join

Concatenate Concat

Sort orderby, orderbydescending, reverse, thenby, thenbydescending

Group groupby and tolookup

Set distinct, except T, intersect, Union

Converts asenumerable, asqueryable, cast, toarray, todictionary, and tolist

Equivalent to sequenceequal

Elements: elementat, elementatordefault, first, firstordefault, and last

Lastordefault, single, singleordefault

Generate defaultifempty, empty, range, repeat

Quantity: All, any, and contains

Aggregate aggregate, average, Count, longcount, Max, Min, Sum

3.4 query expression

Query operators refer to static methods used to form queries. However, the following syntax is not applicable when writing a query:

var processes =Process.GetProcesses().Where(process=>process.WorkingSet64>20*1024*1024).OrderByDescending(process=>process.WorkingSet64).Select(process=>new{process.Id,Name=process.ProcessName});

Another syntax is to make the LINQ query more like an SQL query statement.

var processes =from process inprocess.GetProcesses()whereprocess.WorkingSet64>20*1024*1024orderbyprocess.WorkingSet64 descendingselect new {process.Id,Name=process.ProcessName };

The preceding statement is called a query expression or a query syntax.

3.4.4 restrictions

In a LINQ query, we use both the query operator and the query expression. However, even when using a query expression, you may have to use some query operators. Because the query expression syntax and keywords only support part of the query operator function. When writing a query expression, we also use some query operators as necessary.

C # the compiler translates the query expression into the calling of the following query operators: Where, select, selectmany, join, groupjoin, orderby, orderbydescending, thenby, thenbydescending, groupby, and cast.

 

3.5 Expression Tree

Iqueryable, another method to implement delayed query execution

Using ienumerable <t> and iterator is a method to implement delayed query execution. Another method to implement delayed query execution is the expression tree.

This method of delayed query execution is used in linqto SQL. For the code that has appeared in Chapter 1 below, the program will not start to execute the SQL statement until the foreach loop begins to traverse the contacts variable:

3.6 LINQ assembly and namespace

Some of the classes and interfaces required to use LINQ are defined in the collections (DLL) released along with. Net 3.5 ). Therefore, if you want to use it in a program, you must wait until the Assembly to be referenced and import the namespaces.

The most important assembly is system. Core. dll. If you want to use the functions related to LINQ toobjects, You need to import the system. LINQ namespace it contains. In this way, we can use various standard query operators defined in system. LINQ. enumerable. Note that when you use Visual Studio 2008 to create a new project, the system. Core. dll assembly has been added to the project reference by default.

This section briefly introduces the components, namespaces, and content contained in LINQ.

Conclusion 3.7

We have introduced in detail the methods for extending the C # and VB. NET frameworks of LINQ. Summary:

The sequence, that is, the iterator in LINQ;

Delayed query execution;

Query operator, that is, the extension method for implementing query operations in the context of LINQ;

Query expression, which is similar to SQL from... Where... Syntax;

Expression Tree, used to represent queries in the form of data, and thus support higher scalability requirements.

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.