Introduction to LINQ

Source: Internet
Author: User


Language-Integrated Query (Language INtegrated query,linq) is a Microsoft technology that adds a natural query of SQL syntax to the. NET Framework programming language, which supports visual Basic. NET and the C # language.

Technically, LINQ defines about 40 query operators, such as Select, from, in, where, and order by (C #). Use these operators to write query statements. However, these queries can also be based on many types of data, and each data type requires a separate LINQ type.

Over the past 20 years, the application of object-oriented programming (object-oriented) programming technologies in industry has entered a stable stage of development. Programmers now agree with language features like classes (classes), Objects (objects), methods (methods). Looking at current and next-generation technologies, a major challenge for a new programming technology has begun to emerge, when object-oriented technology was born without addressing the complexity of reducing access and consolidating information data (accessing and integrating information). Of these, two of the most important data sources are related to the database and XML.

LINQ provides a more general way to add some syntax query features (general-purpose) to the. Net framework that can be applied to all sources of information (all sources of information) (query Faci Lities), which is a better way to add some relational data (relational) attributes or similar XML attributes (xml-specific) to the development language and runtime (runtime). These syntax attributes are called. NET Language Integrated Query (LINQ).

Contains DLinq and XLinq.

==================

1. Linq Reading Method: (1) Lin K (2) Lin Q

2. Linq keywords: From, select, in, where, group by, ...

3. Linq Note: Must end with select or group by.

4. The syntax for LINQ:

1) from temp variable in implement Ienumerable<t> interface object

Where Condition expression

[Conditions]

[GROUP BY conditions]

The value queried in the Select Temp variable

2) The object that implements the Ienumerable<t> interface. The LINQ method name (lambda expression). Such as:

string input = "Hellow world";

int count = input. Count (w=>w = = ' O '); Query the number of occurrences of the letter O

objects that can use LINQ need to implement the Ienumerable<t> interface. and LINQ query expressions are compiled at the time the object is created.

5. Full name of LINQ: Language-integrated Query

6. Namespace: System.Linq;

Note: LINQ is a technology that appears in the. NET Framework 3.5, so you must choose 3.5 or higher when creating a new project, otherwise you will not be able to use it.

After you select the. NET framework of 3.5 or later, the System.Linq namespace is automatically included in the new project that you create.

=========================

Syntax instances

c#3.0 LINQ query syntax

Let's start with a simple LINQ query example that queries for numbers less than 5 in an int array and sorts them in order of size:

classprogram{Static voidMain (string[] args) {int[] arr =New int[] {8,5, the,3, About,4,1, - }; varm = fromNinchArrwhereN <5  byNSelectN; foreach(varNinchm) {Console.WriteLine (n);  } console.readline (); }}

The above code, in addition to the LINQ query syntax, is the syntax we are familiar with, and the LINQ query syntax is similar to SQL query syntax, except in order of precedence.

Q: Why does the LINQ query syntax start with the FROM keyword, rather than the SELECT keyword? Select at the beginning of this kind of writing and SQL is more similar to the wording, more understandable?

A: Simply put, for the IDE's IntelliSense (intelisence) feature, the SELECT keyword is behind.

The programming language writes the LINQ query syntax with a select that does not appear, if you have used the VB9 CTP version for 2005 years, then the LINQ query syntax for VB9 is the SELECT keyword in front, but the SELECT keyword is in front, It's very big when it comes to IntelliSense (Intelisence). After the Microsoft IDE Group trade-offs, the FROM keyword is determined to be the first.

The query syntax for VB9 LINQ was at the top of the Select parameter. But later the VB9 beta was changed to the same approach as C #, with the FROM keyword on the front.

A more detailed explanation comes from assembling the head

Suppose you want to write a code like this: Select P. Name, p.age from p in persons Where XXX, the code is entered as a single character.

Before we write to p in persons, the type of p cannot be inferred, so a property such as name does not pop up smart hints when writing Select p.

This will require the first to write from this sentence, and then come back to write Select.

The Microsoft IDE Group has been thinking over and over again, so it's better to write the Select to the back. So the writing in the programming language is sure to write like this.

VB9 's changes can be see this blog:

Select/from vs. From/select revisited ...

Let's look at a slightly more complex LINQ query:

In our list of language strings, we want to sort by the length of the characters, the implementation code is as follows:

Static voidMain (string[] args) {string[] languages = {"Java","C #","C + +","Delphi","VB. NET","VC. NET","C + + Builder","Kylix","Perl","Python"}; varquery = fromIteminchLanguages byItem group item by item. Length into Lengthgroups byLengthgroups.key DescendingSelectlengthgroups; foreach(varIteminchquery) {Console.WriteLine ("strings of length {0}", item.    Key); foreach(varValinchItem)    {Console.WriteLine (val); }} console.readline ();}

The INTO keyword indicates that the result of the previous query is considered a generator for subsequent queries, which is used with group by.

Group BY in LINQ is not confused with group by in SQL because it is a two-dimensional structure, and some of the logic of group by is constrained by a two-dimensional structure that cannot be as flexible as group by in LINQ.

In fact, LINQ has the following two forms of query syntax:

Query method: (Methord Syntax)

The main use of the extension method defined in the System.Linq.Enumerable class and the lambda expression way to query

Query statement mode: (query Syntax) A query method that is closer to the SQL syntax, which is more readable.

=============================
Principle Analysis

LINQ (Language Integrated Query) is a leading figure in Visual Studio 2008. With LINQ technology, we can query any form of data using a SQL-like syntax. LINQ supports data sources such as SQL Server, Oracle, XML, and in-memory data collections. Developers can also add more data sources, such as MySQL, Amazon, or even googledesktop, using the extension framework they provide.

In general, an important feature of such query statements is the ability to parallelize execution. While there are some situations where parallelism can cause some problems, this is a rare situation. This also leads to the process of PLINQ's LINQ class library, which is parallel processing.

PLINQ, formerly known as parallel LINQ, supports XML and in-memory data collections. The query statements executed on the remote server, such as LINQ to SQL, obviously do not implement this functionality.

Converting a LINQ statement to a PLINQ statement is extremely straightforward--you only need to add the last of the data sources specified in the FROM clause in the query statement. AsParallel (). The Where, by and select clauses are then automatically changed to call this parallel LINQ version.

As described in MSDN Magazine, PLINQ can be executed in three different ways. The first is pipeline processing: one thread is used to read the data source, while the other threads are used to process query statements, both synchronously-although this single consumer thread may not be so easy to synchronize with multiple line threads. However, if you can carefully configure the load balance, it will still greatly reduce memory consumption.

The second mode, called "Stop and Go," is used to process a result set when it needs to be returned once (for example, by calling ToList, ToArray, or sorting the results). In this mode, each process is completed sequentially and the results are returned uniformly to the consumer thread. This pattern will outperform the first mode in performance because it eliminates the overhead of keeping threads synchronized.

The last method is called "inverted enumeration". The method does not require the implementation to collect all the output and then process it in a single thread, but instead passes the final called function through the forall extension to each thread. This is the fastest processing mode, but this requires that the functions passed to ForAll are thread-safe, and it is best not to include any mutually exclusive statements such as lock.

If any one of the threads in PLINQ throws an exception, all other threads will be terminated. If more than one exception is thrown, these exceptions will be combined into an multiplefailuresexception type exception, but the call stack for each exception will still be preserved.

=======================

Advantages of Use

1. No complicated learning process can be started

2. Write less code to create a complete app.

3. Develop applications with fewer errors faster.

4. You can merge data sources without resorting to strange programming techniques.

5, let the new developer more efficient development.

6, any object or data source can be customized to implement the LINQ adapter, for data interaction to bring real convenience.

Introduction 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.