Linq in action

Source: Internet
Author: User

There are two writing methods for Linq, one is similar to the SQL style, called the Query Expression), and the other is implemented by using the extension method, called the method Syntax Fluent Syntax ). As follows:

 
 
  1. String [] fullNames = {"Anne Williams", "John Fred Smith", "Sue Green "};
  2. // The query expression is written as follows:
  3.  
  4. Var query =
  5. From fullName in fullNames
  6. From name in fullName. Split ()
  7. Orderby fullName, name
  8. Select name + "came from" + fullName;
  9.  
  10. // Method Syntax:
  11.  
  12. Var query = fullNames
  13. . SelectMany (fName => fName. Split (). Select (name => new {name, fName }))
  14. . OrderBy (x => x. fName)
  15. . ThenBy (x => x. name)
  16. . Select (x => x. name + "came from" + x. fName );

The two are actually equivalent. Because. net does not really understand the query expression, the compiler converts the query expression to the method syntax during program compilation, that is, calling the extension method.

-------------------------------------

Speaking of Linq, we have to say two interfaces, IEnumerable <T> and IQueryable <T>. The data that can be queried by Linq must be a set and the IEnumerable <T> interface is implemented .. Almost all generic sets in. NET implement the IEnumerable <T> interface. IQueryable <T> inherits from IEnumerable <T>. Therefore, IEnumerable <T> can be implemented, and IQueryable <T> can also be implemented.

Differences between the twoThe main reason is that IEnumerable is used to operate data in the memory of Linq., Such as Linq to object,IQueryable is used for external data.For example, Linq to SQL.

When using Linq to SQL, the compiler uses the provider in IQueryable,Translate a query expression into a query statement that matches the data source, such as an SQL statement.When using Linq to object, the data source is IEnumerable and there is no provider at all. In fact,. NET implements query through extension methodsFor example, the Where <T> () method essentially uses the MoveNext () method of the iterator to traverse and judge each element.

----------------------

Expressions and statements

Simply put, an expression can only be a single statement and has an output value. The statement is a block consisting of multiple sentences or.

In. NET, Expression <TDelegate> is a generic Expression that accepts a delegate. Only one Lambda expression can be assigned a value to the expression type. However, if it is a Lambda expression that contains a statement block, it cannot be assigned a value to the expression type.

Expression <Func <Object, Object> identity = o => o;

Expression <Func <Object, Object> identity = o =>{ return o ;}; // Error

The above example shows that the Expression type is similar to the delegate type, and the delegate type can be defined as follows.

Func <Object, Object> identity = o => o;

Although it seems that the variable names and values are the same. NET compiler knows the differences between Expression <TDelegate> type and delegate type. It does not directly compile lambda expressions into IL code, but generates some IL, these IL represents the expression directory tree of the lambda expression. Of course, we can also encode these expression trees manually.

The expression is actually an abstract syntax tree (AST). in computer science, an abstract syntax tree is a data structure, which is often used in compilers or interpreters. The purpose of converting a Lambda expression into an abstract syntax tree is that some code can analyze this expression and perform different operations. During running, expressions can be converted by tools, such as converting to SQL in the case of Linq to SQL.

IQueryable type extension methods such as Where and Select. All accepted parameters are expression types,

The Extension Method of the IEnumerable type accepts the parameter of the delegate type. For example:

Public static IEnumerable <TSource> Where <TSource> (this IEnumerable <TSource> source,Func <TSource, bool> predicate);

Public static IQueryable <TSource> Where <TSource> (this IQueryable <TSource> source,Expression <Func <TSource, bool> predicate);

Therefore:

List <int> lst = new List <int> {1, 2, 3, 4, 5, 6, 7 };

Var result1 = lst.AsEnumerable(). Select (x => {return x;}); // correct

Var result2 = lst.AsQueryable(). Select (x => {return x;}); // Error

Var result3 = lst. AsQueryable (). Select (x => x); // correct

Linq is delayed, for example, the following code:

 
 
  1. static void Main(string[] args)  
  2.         {  
  3.             List<int> lst = new List<int> { 1, 2, 3, 4, 5, 6, 7 };  
  4.             var result = lst.Select(x => doubleit(x));  
  5.         }  
  6.         static int doubleit(int x)  
  7.         {  
  8.             Console.WriteLine("double " + x);  
  9.             return x + x;  
  10.         } 

After running, we found that the doubleit method was not running at all. Modify the Code as follows:

 
 
  1. List<int> lst = new List<int> { 1, 2, 3, 4, 5, 6, 7 };  
  2. var result = lst.Select(x => doubleit(x));  
  3. foreach (var n in result)  
  4.        Console.WriteLine(n); 

This is because the IEnumerable Select Extension Method in Linq is essentially an iterator. When the Select result is assigned to a variable, the query is not performed immediately, it is only a potential query. Only when the iterator is foreach can MoveNext really judge and run the data. This is also true for the Where extension method.

-------------------------------------------

Custom Linq Provider

The following example demonstrates the custom implementation of Linq Provider.

For classes that implement the IEnumerable interface, you only need to implement the GetEnumerator method.

For classes that implement the IQueryable <Folder> and IQueryProvider interfaces, CreateQuery and Execute must be implemented.

Custom Linq Provider is complex. For more information, see

Http://blogs.msdn.com/mattwar/archive/2007/08/09/linq-building-an-iqueryable-provider-part-i.aspx

Learning. You also need to learn some knowledge about DLR and be familiar with expression classes. I don't know much about it. I still need to learn.

References: LINQ IN ACTION

This article is from the "one blog" blog, please be sure to keep this source http://cnn237111.blog.51cto.com/2359144/1078007

Related Article

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.