In-depth study of the series of LINQ to SQL (Basics of LINQ query)

Source: Internet
Author: User

This article is organized from the msdn

I. Concepts of LINQ:
LINQ is short for Language Integrated Query (Language integration query), which is integrated in. netProgramming LanguageThis allows the query expression to get a good syntax check during compilation, rich metadata, and advantages of smart sensing for other strong languages. net Framework Version 3.5 is a groundbreaking innovation that builds a bridge between the object field and the data field.

Ii. Background of the emergence of LINQ:
Traditionally, data-based queries are represented by simple strings, but are not supported by compile-time type checks or intelliisense. In addition, you must learn different query languages for the following data sources: SQL database, XML document, and various web services. By using LINQ, queries are constructed in the first-class languages of C # and Visual Basic. You can use language keywords and familiar operators to write queries for a strongly typed object set. In Visual Studio, you can use Visual Basic or C # To write a LINQ query for the following data sources: SQL Server database, XML document, and ADO.. Net dataset and any object set that supports the ienumerable or generic ienumerable <t> interface. In addition, it plans to support the LINQ of ADO. NET Entity Framework, and the third party providesProgram.

Iii. query expression parsing:

 

Query resolution instances
Int [] Numbers = { 5 , 4 , 1 , 3 , 9 , 8 , 6 , 7 , 2 , 0 }; // Obtain the data source.
VaR lownums = From n In Numbers
Where N <   5
Select N; // Create a query.
Console. writeline ( " Numbers <5: " );
Foreach (VAR x In Lownums) // Execute Query
{
Console. writeline (X );
}

Result:
Numbers <5:
4
1
3
2
0

 

the semantics is equivalent to the following query methods
var lownums = numbers
. where (S => S <5)
. orderby (S => S)
. select (S => S);
before proceeding, let's first introduce some basic knowledge about func generic delegation. This is. net helps us define a form of delegation.
func (T, tresult) generic delegation: encapsulate a method that has a parameter and returns the type value specified by the tresult parameter. The format of the delegate is as follows:
Public Delegate tresult func (T Arg)

There are four types of func generic delegation:
Func (T1, T2, tresult) generic delegation
Func (T1, T2, T3, tresult) generic delegation
Func (T1, T2, T3, T4, tresult) generic delegation
The Lamda expression is actually equivalent to the following anonymous delegate:
Func <int, bool> filter = delegate (INT s) {return S <5 ;}; // equivalent to S => S <5
Func <int, int> extract = delegate (INT s) {return s ;}; // equivalent to S => S
Func <int, int> Get = delegate (INT s) {return s ;}; // equivalent to S => S
VaR lownums = numbers. Where (filter). orderby (extract). Select (get );
The where method is an extension method defined in the system. LINQ namespace.

 

Where source code
Namespace System. LINQ
{
Public   Static   Class Enumerable
{
Public   Static Ienumerable < Tsource > Where < Tsource > (
This Ienumerable < Tsource > Source,
Func < Tsource, Bool > Predicate)
{
Foreach (Tsource item In Source)
{
If (Predicate (item ))
{
Yeild Return Item;
}
}
}
}
}

 

The predicate here is the lambda expression you pass in. Where will filter data based on this Lambda expression.

All LINQ query operations are composed of the following three different operations:
1. Obtain the data source.
2. Create a query.
3. Execute the query.

Data source:
In the previous example, because the data source is an array, it implicitly supports the generic ienumerable <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 <t> ). The types that support ienumerable <t> or derived interfaces (such as generic iqueryable <t>) are called "queryable types ".

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 expression in the previous example 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. 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.

Run the query:
In the preceding example, the foreach loop is the execution process of LINQ. The execution query in LINQ is divided into two types: Forced immediate execution and delayed execution. We will explain it in detail in future sections.

Iv. LINQ and generic types
Based on the generic type, the generic type is introduced in. NET Framework 2.0. You do not need to know more about generics to write queries. However, you may need to understand two basic concepts:

1. When you create an instance of a generic collection class (such as list <t>), replace "T" with the type of the object contained in the list. For example, the string list is represented as list <string>, and the customer Object List is represented as list <customer>. The generic list is strongly typed and provides more benefits than storing its elements as a collection of objects. If you try to add the customer to the list <string>, an error occurs during compilation. The reason why generic collections are easy to use is that you do not have to perform forced type conversion during runtime.

2. ienumerable <t> is an interface through which you can use the foreach statement to enumerate generic collection classes. Generic collection classes support ienumerable <t>, just like non-generic collection classes (such as arraylist) Support ienumerable.

All the LINQ query variables implement or inherit the ienumerable <t> interface, such as iqueryable <t>. When you see the query variable converted to ienumerable <customer>, this only means that when the query is executed, the query generates a sequence containing zero or multiple customer objects.

 

Code
Ienumerable < Customer > Customerquery =
From cust In MERs
Where Cust. City =   " London "
select Cust;

foreach (customer in customerquery)
{< br> console. writeline (customer. lastname + " , " + customer. firstname);
}

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.