. NET in-depth parsing of the LINQ framework (II: The Prelude to LINQ Elegance)

Source: Internet
Author: User

Read the catalogue:

    • The main design model of 1.LINQ frame
      • 1.1. Chained design mode (System logic is designed in a pipelined way)
      • 1.2. Chained Query method (stepwise processing of each work point in a query expression)
    • Core design principle of 2.LINQ frame
      • 2.1. Languages above the Managed language (LINQ query expressions)
      • 2.2. The foundation of a managed language construct (the LINQ dependency Common interface corresponds to the method of the query operator docking)
      • 2.3. In-depth IEnumerable, ienumerable<t>, Enumerable (the entry to the LINQ to object framework)
      • 2.4. In-depth IQueryable, iqueryable<t>, queryable (the entry to the LINQ to provider framework)
      • 2.5.LINQ query interface for different data sources
      • 2.6. The framework principle of overall grooming LINQ
1 ". The main design model of the LINQ framework

Here we seem to be vaguely able to see the principle of LINQ, which is not an aerial garden, it has a foundation. With the support of a series of new features above, Microsoft has built a large-scale method of building extension to make the above-mentioned features interact coherently and form a natural integrated query framework. All of these features are language enhancements for LINQ, and designers are constantly exploring new language features that are more consistent with modern development systems, as well as increasing support for functional programming features such as the introduction of the DLR to Python, Ruby's functional scripting language, There will be more and more support for other functional scripting languages later.

Below we will mainly learn the object model of the relevant knowledge, what is the object model? In fact, many times we pay attention to the language level of learning and do not focus on the object of design principles, resulting in increasing learning costs. We should be more important to learn and develop design capabilities (so-called design capabilities reflect the technical level). Object model simple point is the object design model, how to construct the deep object structure that satisfies the need. At the moment. The main ORM Framework on the NET platform the design of the conceptual layer in the architecture system in the entityframework is embodied the function of the object model. There are many object models in the ADO EntityFramework, LINQ to SQL framework that are worth exploring.

There are a lot of extension methods in LINQ, and in the back of these extension methods there is a big design secret, and that is the chained programming model, which we will use in a detailed learning chain programming model to understand why LINQ is so graceful in using the same method consistently.

    • 1.1. Chained design mode (System logic is designed in a pipelined way)

The chain design pattern is a very graceful pattern that we have been ignoring, and the last time we touched it was when we were learning LINQ, I saw that it was really impeccable to see a coherent extension approach coming in. In fact, in many cases we can learn from this design pattern, can be very natural to deal with a lot of difficult problems. A more daring design is to use chain mode after the fragmentation of the business algorithm for the artificial logical reorganization, if the design is good, it will be a top feast. Since this article is about the content of LINQ, I'm not going to talk about it here, there will be a special article to explain the bold chain business process reengineering knowledge.

In many cases when we design a system function or application framework, we can use the chain design mode to elegant our development way, so that the coding is very convenient.

In order to express the use of the chain design pattern very vividly, here I use a relatively simple small example to show its design concept and use.

Example: Suppose I have an object type that represents a student and a type that represents the student collection. Student collection type is mainly used to accommodate student entities, the collection type provides a series of methods can be used for continuous operation of this set, it is very common to filter operations. For example, the selection of all sex is a girl student, and then in all the selected female students in the collection of the age of more than 20 years old student list, and then continue to screen from Jiangsu Nanjing area student list and so on this series of coherent operation. This approach I think is the most common LINQ, after all, LINQ is for querying, and the query is mainly for the collection class data.

Object graph:

The properties and methods in each object can be clearly seen in the object graph, and we have defined several basic student attributes in the student class. In Studentcollection, it is important to Selectbyfemale method and Selectbymankind method, which are the methods of screening students ' gender as female and male, The other thing is that selectbyage and selectbyaddress are used to filter the age and address respectively. Because the specific method code is relatively simple here is not posted out, the purpose is to let everyone can intuitively see the advantages of the chain design model and flexible place.

Example code:

View Code

It seems to be not very elegant, I feel very elegant and comfortable anyway. In fact, when we design the internal method of the Studentcollection object, there may be a place very awkward, that is, each return type of the method must be able to make the next method call smoothly, so you must keep each method call is the same data type, That is, the Studentcollection collection type.

Most of the time our design thinking has a blind spot, that is, each return and this time does not matter, chain programming seems to find this blind spot and very serious with our emphasis on regular to exercise this design blind spot. We use the mind map to analyze the blind spots of the chain design, and also to find out the design advantages we often overlook.

Mind Mapping:

Each method has a return type, but as long as it is guaranteed that the returned type can be an operand of the next method, it is necessary to split the large process into a small, organized process when designing the object method. Many times we design the object model when it is difficult to think of these, in fact, we are not skilled enough, we have to do is more practice to see the design of the book, the rest of the time it.

    • 1.2. Chained Query method (stepwise processing of each work point in a query expression)

In the chain design pattern above, we probably learned that if you build a loop-forming object model, you can repeatedly use object collections to perform duplicate query operations. In fact, LINQ is using this approach as its query principle. This will be directly humorous to the core design principles of LINQ. The chain model of LINQ is mainly used on the collection of Query objects, and the large-area building extension method allows the object to fill the query method for the LINQ expression that can be used.

So how do we understand LINQ queries? Most of the comrades know the syntax of LINQ, which is "from * * * * * * * * * * * * *" like SQL. In fact, this is a new query syntax built with the CTS that is handled by the editor, which is not a managed language such as C # or vb.net. In fact, we all know C #, VB. NET syntax are based on the. NET Platform Il Intermediate language, they are part of the source code, not the final output of the program. And IL is the program code of the output item after each compile. The syntax of LINQ is finally the syntax of IL, and when we write a query expression for LINQ, the editor has intelligently translated the methods for us into objects. Too many principles are introduced in the next knot.

On the chain Query method is also an object design problem, we see the chain design pattern can be very natural to build in line with our own actual needs of the chain query method, the addition of a series of query methods there is a big problem is not dynamically added to the object to be extended inside. For example, the published object can not be directly modified, so here is the extension method we mentioned above, through the extension method we are very convenient to add the behavior of the published objects. In order to be persuasive, we should look at a little to reinforce the impression.

Example: Let's say I have a set of easy-to-release ORM components that are built in. NET2.0, now I need to expand it into a chain-like query, rather than using the cumbersome query method of the past. So I need to build one alone. The extension of the NET3.0 or. NET3.5 as an extension of the previous assembly can be used or may not be used, so that we can use the extension method or other new syntax features.

View Code

Ormhelper.findentitylist<t>
is a generic method of querying an object list based on an entity's existing properties, which is, of course, a simpler point to demonstrate. If I need to add another condition, it must be the base_deptment type parameter
Model add value to use, now I want to extend it in chained design mode to use as a chained query, such as:

View Code

The code here is just a context-sensitive, and there may be some unreasonable places, but it has no effect.

This makes it possible to design an inherently bloated feature so that it can be used in such an elegant way. For LINQ to Customentity implementation I will have a special article to explain later, here will not be torn down. The example itself is to tell us that we can use chain queries to implement a more user-friendly, elegant component or framework.

2 ". The core design principles of the LINQ framework
    • 2.1. Languages above the Managed language (LINQ query expressions)

Through the above example, we should have a basic understanding of the chain design patterns, chain query method of the mysterious and useful. Through a simple example, we also realize that the chain query method has a unique advantage in data query, which is also a good idea to understand LINQ.

So what does the chained Query method prepare for LINQ? Prepared the corresponding method? Yes, chained design patterns are a good enough theoretical basis for chain queries, and then it is natural to use a large area of constructing chain queries to correspond with the query operators of LINQ query expressions, which makes it an excellent link to query any data source using LINQ. LINQ provides a unified query interface, and then uses a custom chained query method to form a lambda expression of the user's operational data, and then, by extracting the relevant data structures in the lambda expression, to send the data driver query data.

LINQ itself is not a category of managed languages, it is a convenient syntax for editor support to reduce the hassle of using query methods directly. In contrast, if we use the Query method directly then we will pay a lot of effort and time.

Example code:

View Code

There are two ways to query the collection data, the first of which is to query the data using a chained query method. The second is to query the data using a LINQ query expression. There is no doubt that LINQ is convenient, simple and convenient, more in line with our custom SQL query method.

So that we can easily draw a filtered object. The editor is responsible for processing LINQ instead of the CLR, which processes LINQ into the basic set of interfaces implemented by the framework. Remember that LINQ is a syntactic sugar level, and it is not supported by C #, not vb.net, nor the basic kernel of the CLR.

    • 2.2. The foundation of a managed language construct (the LINQ dependency Common interface corresponds to the method of the query operator docking)

LINQ is a unified data query interface, so how does it connect to different data sources directly? In the 4.1 summary, we conveniently queried the specified item in the student[] array through a simple LINQ query expression, how does that work? Let's step through how LINQ does a unified data query.

We now assume that there is no LINQ to look at. NET is how to build a inside that supports LINQ at 1.1 points.

LINQ is introduced in the. NET3.5 release, the core assembly is System.Core.dll, with two namespaces that are directly related to LINQ, System.Linq (the set of linked query methods directly corresponding to LINQ query expressions), System.Linq.Expressions (logical expression tree in Linq query expressions). In System.Linq, the first and foremost is the enumerable static class, which encapsulates the static extension method of the query IEnumerable interface type. It should be noted here that the data source of the LINQ query is mainly divided into two categories, and the first thing that must be supported is LINQ to object, for in-memory object queries are of course the IEnumerable object, and the query is for the collection class. NET is an implementation interface that uses IEnumerable as an iterator object. So the System.Linq.Enumerable static class is all encapsulated in the IEnumerable interface of the chain query method, these methods are provided by the extension method, that is, in the version below. NET3.5, the extension assembly package is not loaded. What is more critical is that all the logical expressions in the extension method are func generic delegates, that is, the direct use of the delegate to perform the logical operation, when we call the form of a lambda to give the logic of the condition, these logic is directly compiled into an anonymous method can be executed, Instead of expression object expressions, the direct invocation of an in-memory object query is OK.

Another type of LINQ-supported query object is our custom data source, which is provided by the System.Linq.Queryable class, if we use a LINQ query expression to query the System.Linq.IQueryable <T> type Object, the editor will assume that you are querying a custom data source object and will invoke the System.linq.iqueryableprovider<t> interface implementation class that you implement when executing. This class provides parsing and execution of an expression tree. A closer look at System.Linq.Queryable the difference between all extension methods in a static class and the extension method in the System.Linq.Enumerable class is that all func types are System.Linq.Expressions.Expression <T> type packaging, which is also in line with our previous article, the analysis of System.Linq.Expressions.Expression as a data structure, when needed, we have to read the relevant logical structure.

Whether you query LINQ to object or a custom data source, the LINQ syntax of the query is constant, which is to unify the data query interface, and to change the data query Provider, LINQ to Sql and LINQ to Entities are all implemented with custom data source query capabilities.

    • 2.3. In-depth IEnumerable, ienumerable<t>, Enumerable (the entry to the LINQ to object framework)

In the 4.2 knot that has been supported for LINQ queries, what is the difference between queries? What is the difference between using ienumerable<t> and iqueryable<t>? How to well understand the relationship between the two in LINQ throughout the framework.

LINQ is a unified data query interface on the. NET platform, no matter what type of data we want to query, and regardless of the data in the network world, we can be very good query. Well, no matter what kind of data we want to query, we need to create a mature object model, if we can still directly drag the data from the server and then a DataTable or a DOM tree, in fact, it is not very meaningful, we need to be able to continuously in memory of the object query. When we query the data from the remote server into memory, we need to use the object model we created to object it and prepare it for LINQ to object. Only LINQ to object can be executed perfectly by LINQ to Custom, which is a reverse relationship.

The generic Ienumerable<t> interface inherits from the IEnumerable interface, which represents a collection of data that can be iterated. Linq to object is also a query ienumerable<t> collection. All static methods in the enumerable static class correspond to LINQ query expressions that manipulate the Ienumerable<t> collection type, and are called directly to the static method inside the enumerable each time the query is invoked. There's really not much to say about LINQ to object, but to be familiar with LINQ's query expression syntax.

    • 2.4. In-depth IQueryable, iqueryable<t>, queryable (the entry to the LINQ to provider framework)

The IQueryable interface is provided to us to implement a custom data source, in order to support a strongly typed collection of data sources we use the Iqueryable<t> interface directly when we use LINQ to query the Iqueryable<t> interface, the query expression is compiled directly into the corresponding static extension method in the corresponding queryable static class. The logical condition is treated as a query expression at this time, not as if the Ienumerable<t> interface is directly a delegate. Of course, to realize the LINQ query data source is still more difficult, we need to handle the expression tree itself, the following article will be explained in detail.

    • 2.5.LINQ query interface for different data sources

So far I think we all have a general understanding of LINQ Unified Data Source Query, no matter what our data source is, RDMS, Dom, and so on, we all have a corresponding query method, hard just encapsulated people, do background development friends may need to use these specialized query language to query data, It is convenient for front-end programmers to query data sources using LINQ.

The primary task for component developers is to create an object model, which should be an abstract model of a true data source, so that the object may successfully be put into iqueryable<t> for querying.

    • 2.6. The framework principle of overall grooming LINQ

Through the above detailed introduction of the framework of LINQ to our basic grasp, if only to use it is very simple, as long as the familiar LINQ query syntax is OK, but I think each of us programmers have a very strong curiosity, want to understand the framework of the design principle, which is we must have the combat effectiveness.

The LINQ query expression is finally called the chained Query method, which is defined in the static class,ienumerable<t> type is directly executed using anonymous method invocation, and iqueryable<t> is the use of manual parsing method, That is, a custom data source. There are also some lightweight query libraries that are excellent examples of extended data sources, such as LINQ to XML, LINQ to SQL, LINQ to Entities, and so on, which are worth digging into.

. NET in-depth parsing of the LINQ framework (II: The Prelude to LINQ Elegance)

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.