LINQ (1) LINQ queries

Source: Internet
Author: User
ArticleDirectory
    • 1. Get start
    • 2. latency mechanism (deferred/lazy execution)
    • 3. subquery)

Language Integrated Query is a group of technical names that allow us to write type-safe query statements to query local objects or remote data sets. The premise of using LINQ is that the collection you need to query implements the ienumerable <t> interface. The technologies included in LINQ include local object query (LINQ to object), XML query (LINQ to XML), and database query (LINQ to SQL). We can alsoProgramExtend the implementation of LINQ, for example, to Lucene.

1. Get start

The basic elements of LINQ are squences and elements. squencens. Any object that implements the ienumerable <t> interface, and element is each object that makes up the squences. There are three methods of writing the same effect in LINQ: Lambda expression writing (for the time being, this is called it), extenstion method and fluent syntax ).

// Get the name 'length over four. string [] names = {"Jack", "hanmeimei", "lilei", "Amy"}; ienumerable <string> filterednames1 = enumerable. where (names, n => N. length> 4); ienumerable <string> filterednames2 = names. where (n => N. length> 4); ienumerable <string> filterednames3 = from name in names where name. length> 4 select name;

 

The first method is lambda expression and the most primitive method. This class uses enumerable (this class is defined in system. the query operater defined by a series of static methods in the LINQ namespace) for query, the second extension method is extended by using the new features (fetures) of C #3.0, and the third query expression (query expression syntax) it is the "syntactic Sugar" (IL) provided by vs2008.CodeIs it 1? 2 ?) This allows us to write Query expressions like SQL statements.

So why do we need to write extension methods? Because we may need to filter a set, and the extension method provides convenience for chaining querying operators ).

// Get the name 'length over four the sort then by name' length then Upper toupper. string [] names = {"Jack", "hanmeimei", "lilei", "Amy"}; ienumerable <string> filterednames1 = enumerable. select (enumerable. orderby (enumerable. where (names, name => name. length> 4), name => name. length), name => name. toupper (); ienumerable <string> filterednames2 = names. where (n => N. length> 4 ). orderby (n => N. length ). select (n => N. toupper (); ienumerable <string> filterednames3 = from name in names where name. length> 4 orderby name. length select name. toupper ();

It can be seen that the use of lambda expressions is cumbersome and difficult to understand, but the query of the extension method is relatively simple and easy to understand. The use of the query expression syntax is closer to the SQL syntax. (We can see enumerable. select <(of <(tsource, tresult>) (ienumerable <(of <(tsource>), func <(of <(tsource, tresult> )) the second parameter of is func <t> (tsource, tresult), which is a generic delegate, in the system. core. dll contains similar actions and predicate ). In addition to the where operation, the enumerable contains about 40 other operations, such as group and join.

2. latency mechanism (deferred/lazy execution)

The result of the LINQ query is not obtained when a query is created, but obtained when a foreach is performed during enumeration.

// Lazy execution VAR numbers = new list <int> (); numbers. add (1); ienumerable <int> result = numbers. select (n => N * 10); numbers. add (2); foreach (VAR number in result) {console. writeline (number);} // print 10, 20
 
If you want to obtain the result immediately after the query, you can use the conversion operators (Convertion opertators) such as tolist, tolookup, toarray, todictionary.
 
 
// Lazy execution VAR numbers = new list <int> (); numbers. add (1); ienumerable <int> result = numbers. select (n => N * 10 ). tolist (); numbers. add (2); foreach (VAR number in result) {console. writeline (number);} // print 10
Of course, there are exceptions. If a single result or a value is returned during a LINQ query, there is no delay mechanism, such as Count and first.
 
VaR names = new list <string> (); names. add ("Lili"); names. add ("kated"); names. add ("Amy"); names. add ("lilei"); int COUNT = names. where (n => N. length> 4 ). count (); names. add ("Jakey"); console. writeline (count); // print 2 console. readkey ();
Another important feature of the latency mechanism is to re-evaluate the second foreach operation (reevaluation)
 
// Lazy execution reevaluation VAR numbers = new list <int> {1, 2}; var query = numbers. select (n => N * 10); foreach (var n in query) {console. write (n + "|"); // 10 | 20} numbers. clear (); foreach (var n in query) {console. write (n + "|"); // nothing}
If we need to change the result for the second time, we can use the method mentioned above to add the tolist () operation to the end so that it can return the result set immediately.
 
One of the negative effects of the latency mechanism is that when you use a local variable in the query expression and change the variable before foreach, the results will also change.
// Lazy execution catured variables VAR numbers = new list <int> {1, 2}; int factor = 10; var query = numbers. select (n => N * factor); factor = 20; foreach (var n in query) {console. write (n + "|"); // 20 | 40 not 10 | 20}
 
The implementation of the LINQ delay mechanism is implemented through the decorator. During chained operations, the decoration mode is superimposed.
3. subquery)

LINQ supports subqueries.

// Subquery string [] names = {"Kate", "lilei", "hanmeimei"}; var query = names. orderby (M => M. split (). first (); foreach (VAR name in query) {console. writeline (name); // hanmeimei, Kate, lilei}
 
M. Split (). First () is a subquery. When executing a subquery, LINQ executes a subquery every time the outer layer executes a loop. It has a certain impact on performance.
 subquery and latency mechanism: Use count (), tolist () in subquery () the execution of the outer query is not affected because the subquery is a delegate and does not directly interact with the outer query. 

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.