Start from scratch

Source: Internet
Author: User

It has been a long time since the emergence of LINQ, and it has never been actually used. Sorry, I started to study the usage of LINQ today. The following is transferred from msdn:

A query is an expression used to retrieve data from a data source. Queries are usually expressed in a special query language. Over time, people have developed different languages for various data sources, such as SQL for relational databases and XQuery for XML. Therefore, developers have to learn new query languages for each data source or data format they must support. By providing a consistent model for using data across a variety of data sources and formats, LINQ simplifies this situation. Objects are always used in LINQ queries. You can use the same basic encoding mode to query and convert data in XML documents, SQL databases, ADO. Net datasets,. net collections, and provideProgramAny other formats of data available. The query operation consists of the following three operations: obtain the data source. Create a query. Execute the query. The following example shows how to useSource codeIndicates the three parts of the query operation. For convenience, this example uses an integer array as the data source, but the concepts involved are also applicable to other data sources. This example is also referenced in other parts of this topic.

Code
  Class Program
{
Static   Void Main ( String [] ARGs)
{
// The three parts of a LINQ query:
// 1. Data Source.
Int [] Numbers =   New   Int [ 7 ] { 0 , 1 , 2 , 3 , 4 , 5 , 6 };

// 2. query creation.
// Numquery is an ienumerable <int>
VaR numquery =
From num In Numbers
Where (Num %   2 ) =   0
Select num;

// 3. query execution.
Foreach ( Int Num In Numquery)
{
Console. Write ( " {0, 1} " , Num );
}

}
}

The complete query operation is displayed. In LINQ, the query execution is completely different from the query itself. In other words, if you only create a query variable, no data is retrieved.

Data Source

In the previous example, because the data source is an array, it implicitly supports the generic ienumerable <(of <(T>) interface. This fact means that the data source can be queried using LINQ. Execute the query in the foreach statement, while foreach requires ienumerable or ienumerable <(of <(T>)> ). The types that support ienumerable <(of)> or derived interfaces (such as generic iqueryable <(of)>) are called "queryable type ".

The querytype can be used as a LINQ data source without modification or special processing. If the source data does not appear in the memory as a queryable type, the LINQ provider must represent the source data in this way. For example, you can load an XML document to the queryable xelement type in the LINQ to XML file:

 

 

    //Create a data source from an XML document.
//Using system. xml. LINQ;
Xelement contacts=Xelement. Load (@"C: \ mycontactlist. xml");

 

 

In LINQ to SQL, You can manually or use the object relationship designer (O/R designer) to create an object relationship ing during design. Write a query for these objects, and then the communication with the database is processed by the LINQ to SQL statement at runtime. In the following example, customer indicates a specific table in the database, and table can be derived from ienumerable <(of <(T>) generic iqueryable <(of <(T>)>.

 

 
    Datacontext DB= NewDatacontext (@"C: \ northwind \ northwnd. MDF");

 

 

For more information about how to create a specific type of data source, see the documentation for various LINQ providers. However, the basic rule is very simple: the LINQ data source supports any objects of the generic ienumerable <(of <(T>) interface or the interface inherited from this interface.

 

Query

Query the information to be retrieved from the data source. The query can also specify how to sort, group, and structure the information before it returns. The query is stored in the query variable and initialized with the query expression. To make it easier to write a query, C # introduces a new query syntax.

The query in the previous example returns all the even numbers from the integer array. The query expression contains three clauses: from, where, and select. (If you are familiar with SQL, you will notice that the order of these clauses is different from that in SQL .) The from clause specifies the data source, the where clause applies the filter, and the select clause specifies the type of the returned element. These clauses and other query clauses are discussed in detail in the section of the LINQ query expression (C # programming guide. Currently, you must note that in LINQ, the query variable itself does not perform any operations and does not return any data. It only stores the information necessary to generate results when a query is executed at a later time. For more information about how to build a query behind the scenes, see standard query operator overview.

Query execution

Delayed execution

As mentioned above, the query variable itself only stores the query command. The actual query execution will be delayed until the query variable is cyclically accessed in the foreach statement. This concept is called "delayed execution". The following example demonstrates this concept:

 

 

    //Query execution.
Foreach(IntNumInNumquery)
{
Console. Write ("{0, 1}", Num );
}

 

 

The foreach statement is also used to retrieve the query results. For example, in the previous query, the iteration variable num stores each value in the returned sequence (one value at a time ).

Because the query variable itself never saves the query results, you can execute the query as needed. For example, you can use a separate application to continuously update the database. In an application, you can create a query to retrieve the latest data and execute the query repeatedly at a certain interval to retrieve different results each time.

Force immediate execution

The query that executes Aggregate functions on a series of source elements must first access these elements cyclically. Count, Max, average, and first belong to this type of query. Because the query itself must use foreach to return results, these queries do not use an explicit foreach statement during execution. Note that these types of queries return a single value instead of the ienumerable set. The following query returns the even count of the source array:

 

 

    VaR evennumquery= 
From numInNumbers
Where(Num% 2)= 0
Select num;

IntEvennumcount=Evennumquery. Count ();

 

 

To forcibly execute any query immediately and cache its results, you can call tolist<(<(Tsource>)>)Or toarray<(<(Tsource>)>)Method.

 

 

    List  <  Int  > Numquery2  =  
(From num In Numbers
Where (Num % 2 ) = 0
Select num). tolist ();

// Or like this:
// Numquery3 is still an int []

VaR numquery3 =
(From num In Numbers
Where (Num % 2 ) = 0
Select num). toarray ();

 

 

In addition, you can placeForeachLoop to force the query. However, by callingTolistOrToarrayYou can also cache all data in a single set object.

As shown in the preceding figure, the LINQ syntax is:

VaR variable name = individual in set in from set

Where (conditional expression)

Individuals in the select set;

Specifically, the set must implement the ienumerable interface <t>. By default, the query is executed when the result is needed, or it can be set to immediate execution. In this case, the returned query result is called. tolist or. toarray to save the result set.

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.