Microsoft free book "Introducing Microsoft LINQ" Translation-Chapter1: Statement-based integrated class-based query, Declarative Programming, transparent different class-based systems

Source: Internet
Author: User
Document directory
  • Declarative statement
  • Type Lookup
  • Different types of systems are transparent
  • Type checking
This book is intended for personal learning and knowledge sharing. The copyright of this book is owned by the original author. If there is any infringement, please inform me that I will handle the post immediately.
Reprinting is allowed, but this copyright statement is not allowed for commercial purposes!
Please correct me!

Blog site: cdplayer connection: blog site: Han xilong


Classical language integration is the most basic feature of LINQ. In C #3.0 and Visual Basic 9.0, the generic style of the query tables of LINQ makes you feel the difference of this new feature. It allows you to perform the following operations ︰

VaR query =
From C in mers MERs
Where C. Country = "Italy"
Orderby C. Name
Select New {C. Name, C. City };

To replace the following generation:

VaR query =
MERs
. Where (C => C. Country = "Italy ");
. Orderby (C => C. Name)
. Select (C => New {C. Name, C. City });

Because it uses a more complex method to describe the data query, many people use it as a "sugar-added method ". However, in reality, it is not as simple as we can see. in a short period of time, line-based response is supported by many messaging mechanisms and methods. Under this representation, it uses new technologies such as local type inference, extension methods, lambda expressions, object initialization expressions, and anonymous types. These machines play their respective roles, but if you look at them from a global perspective, you will find that they have made a huge step in both aspects: 1. make the token more "declarative"; 2. reduce the "impedance mismatch" between the number and generation ".

Declarative statement

Difference between the SQL query and the corresponding local data volume operation in C #2.0 or visual basic 8.0 (for example, tableor array for C # Or Visual Basic) what is it?
When SQL is used, you will continue with the following generations ︰

Select * from MERs where country = 'italy'

Using C #, you may think like this ︰

Public list <customer> italiancustomers (customer customers [])
{
List <customer> result = new list <customer> ();
Foreach (customer C in mers ){
If (C. Country = "Italy") result. Add (C );
}
Return result;
}

C # For example, how to calculate the data table at a specific point during a long period of time. In SQL, describe what you want ". In C #, describe how to get the expected result. In SQL, selecting the most efficient algorithm to perform the "how" Operation (more explicit in C #) is to check the role of the engine. This is because the SQL query engine has more quota space than the limit on the C # compiler.
Note:
The functions of the previous C # example are as follows. NET 2.0 can be implemented through the find method, but for most developers, it is not easy to parse the necessary anonymous agent statement. However, the example shows the difference between different processing procedures. With LINQ, C #, and Visual Basic, you can publish a token that is more declarative, its lookup interface describes data-based operations through a "declarative" structure, rather than the original method of repeated and complex operations. LINQ allows a digital business to be more straightforward and clear, at the same time, this clearer business model is the basis for providing higher water services.

Let me think about the parallel problem:
An SQL query can be divided into two parts for calculation, because its data table profiling algorithm does not have any restrictions. However, a C # foreach statement is split into several parallel statements that are not used in the cycle.
More messages
Parallel LINQ (Plinq) is a research concept on parallelism. It can be realized through the LINQ ‑n‑n‑n‑n‑n‑n‑n‑n‑native. The declarative scheduler can make good use of the service capabilities and architecture provided by the scheduler, making it easier for the Agency to renew and renew the scheduler. This should be one of the most important features because it improves the development efficiency of programmers. For example, if you want to obtain all the available failover methods in the application, an ienumerable <t> is returned.
You can use the reflection mechanism to compile the following query results ︰

VaR query =
From assembly in appdomain. currentdomain. getassemblies ()
From type in assembly. gettypes ()
From method in type. getmethods ()
Where method. isstatic
& Method. returntype. getinterface ("ienumerable '1 ")! = NULL
Orderby method. declaringtype. Name, method. Name
Group Method by new {class = method. declaringtype. Name,
Method = method. name };

The equivalent C # generation sequence does not have to grow, and it is easier to generate some linear sequence. Let's take a look at a C # generation that has not been optimized.
1-10

List <string> Results = new list <string> ();
Foreach (VAR assembly in appdomain. currentdomain. getassemblies ()){
Foreach (VAR type in assembly. gettypes ()){
Foreach (VaR method in type. getmethods ()){
If (method. isstatic &&
Method. returntype. getinterface ("ienumerable '1 ")! = NULL ){
String fullname = string. Format ("{0}. {1 }",
Method. declaringtype. Name,
Method. Name );
If (results. indexof (fullname) <0 ){
Results. Add (fullname );
}
}
}
}
}
Results. Sort ();

Type Lookup

Another important feature of classical analytics integration is classification lookup. When a data volume is returned by a LINQ operation, it does not need to perform any unsafe response. The seemingly short Query type table does not ignore the class-type query: All data types are class-type, regardless of the individual entity in the retrieved set or return value. In the statement that supports LINQ (currently C #3.0 and Visual Basic 9.0), type-Based Query exists in each processing process of LINQ. This allows Visual Studio features (such as intelliisense and refactoring) to be used during the debugging of intellij idea, these Visual Studio features play an important role in the development efficiency of programmers.

Different types of systems are transparent

When you look at Microsoft. NET Framework and sqlserver's type systems, you already see their differences.
When using LINQ, you should grant. net class systems are more advanced, because this class system is supported by all the development languages that provide LINQ (C #3.0 and Visual Basic 9.0. Maybe you may have a question: most data types are stored in the relational data centers, at the same time, you have to merge multiple types in different systems. These questions have long been explained to you by LINQ, which will automatically handle these problems for you, these types of systems are almost invisible to programmers.

More messages
There are all limitations in coding between different types of systems and LINQ. About this information, as mentioned in chapter 5th, you can find a more complex table describing system compatibility in the product documentation.

Language
Integration

Language integration is a fundamental aspect of LINQ.
Most visible part is the query expression feature, which is present in C #3.0
And Visual Basic 9.0. It allows you to write code such as the following:

var query =
from c in Customers
where c.Country == "Italy"
orderby c.Name
select new { c.Name, c.City };

Instead of writing this Code:

var query =
Customers
.Where( c => c.Country == "Italy" );
.OrderBy( c => c.Name )
.Select( c => new { c.Name, c.City } );

Registrant people call this simplificationSyntax
Sugaring
Because it is just a simpler way to write code that defines a query
Over data. However, there is more to it than that. Using language constructs and
Syntaxes are necessary to support what seems to be just a few lines of code that
Query data. Under the cover of this simple query expression are local type
Inference, extension methods, lambda expressions, object initialization
Expressions, and anonymous types. All of these features are useful
Themselves, but if you look at the overall picture you shoshould see that there is
A big step in two directions ctions: one moving to a more declarative style of coding,
And one lowering the impedance mismatch between data and code.

Declarative
Programming

What are the differences between an SQL query and
Equivalent C #2.0 or visual basic 8.0 program that filters data contained in
Native storage (such as a table for SQL or an array for C # Or Visual Basic )?

In SQL, you can write the following:

SELECT * FROM Customers WHERE Country = 'Italy'

In C #, you wowould probably write this:

public List<Customer> ItalianCustomers( Customer customers[] )
{
List<Customer> result = new List<Customer>();
foreach( Customer c in customers ) {
if (c.Country == "Italy") result.Add( c );
}
return result;
}

C # Code takes longer to write and read. But the most important
Consideration is expressivity. in SQL, you describeWhat
You want. in C #, you describeHowTo obtain the expected
Result. In SQL, the selection of the best algorithm to implementHow(Which is more explicitly dealt with in C #) is
Responsibility of the query engine. This is because the SQL query engine has
More freedom to apply optimizations than a C # compiler, which has more
Constraints onHow.

Note

The previous C # code sample cocould be written in. NET 2.0
UsingFindPredicate, but for your developers
Required anonymous delegate syntax is not very easy to use. However, the samples
Are merely explain strative of the different programming
Paradigms.

LINQ enables a more declarative style of coding for C # and visual
Basic. a linq query describes operations on data through a declarative construct
Instead of an iterative one. LINQ allows the intentions of programmers to be
Made more explicit, and this knowledge of programmer intent is fundamental
Obtaining a higher level of services from the underlying framework. For example,
Think about parallconfiguration. An SQL query can be split into several concurrent
Operations, simply because it does not place any constraint on the kind of table
Scan algorithm applied. a c #ForeachLoop is harder
Split into several loops over different parts of an array that cocould be executed
In parallel by different processors.

More Info

Parallel LINQ (Plinq) is a research project on
Parallelism that can be obtained by writing code
LINQ.

Declarative Programming can take advantage of services offered
Compilers and frameworks, and in general it is easier to read and maintain. This
Single "feature" can be the most important one because it boosts programmers'
Productiworkflow. For example, suppose that you want to get a list of all static
Methods available in the current application domain that returnIenumerable <t>Interface. You can use LINQ to write
Query over reflection:

var query =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
from method in type.GetMethods()
where method.IsStatic
&& method.ReturnType.GetInterface( "IEnumerable`1" ) != null
orderby method.DeclaringType.Name, method.Name
group method by new { Class = method.DeclaringType.Name,
Method = method.Name };

The equivalent C # code that handles data is longer to write,
Harder to read, and probably more error prone. You can see a possible version
That is not particle ly optimized in listing
1-10.

Listing 1-10: C # code equivalent to a LINQ Query
Over reflection


List<String> results = new List<string>();
foreach( var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
foreach( var type in assembly.GetTypes() ) {
foreach( var method in type.GetMethods()) {
if (method.IsStatic &&
method.ReturnType.GetInterface("IEnumerable`1") != null) {
string fullName = String.Format( "{0}.{1}",
method.DeclaringType.Name,
method.Name );
if (results.IndexOf( fullName ) < 0) {
results.Add( fullName );
}
}
}
}
}
results.Sort();
Type checking

Another important aspect of language integration is type
Checking. Whenever data is manipulated by LINQ, no unsafe cast is necessary.
Short Syntax of a query expression has no compromises with type checking: Data
Is always stronugly typed, including both the queried collections and the single
Entities that are read and returned.

The type checking of the ages that support LINQ
(Currently C #3.0 and Visual Basic 9.0) is preserved even when LINQ-specific
Features are used. This enables the use of Visual Studio features such
Intelliisense and refactoring, even with LINQ queries. These Visual Studio
Features are very important for programmers 'productivity.

Transparency processing SS
Different Type Systems

When you think about the type system of the Microsoft. NET
Framework and the type system of SQL Server, you realize that they are
Different. using LINQ, you give precedence to the. NET type system because it is
The one supported by any language that hosts a LINQ query. However, most of your
Data will be saved in a relational database, and it is necessary to convert Databases
Types of data between these two worlds. LINQ handles this conversion for you
Automatically, making the differences in type systems almost completely
Transparent to the programmer.

More Info

Some limitations exist in the capability to perform
Conversions between different type systems and LINQ. You will find some
Information about this topic in chapter 5, and you can find a more detailed Type System
Compatibilities table in the product documentation.

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.