[Translation] C #3.0 introduction to new features of LINQ

Source: Internet
Author: User
Tags list of attributes valid email address
Translation
AMRO Khasawneh by understanding LINQ (C #)
Flankerfc translation in msproject

Introduction


This article focuses on the most exciting features in the LINQ -- I think vs2008 (. net3.5. The query becomes. net. The queried data can be XML (LINQ to XML), databases (LINQ to SQL, LINQ to dataset, and LINQ to entities) and object (LINQ to objects ). LINQ is also scalable and allows you to create custom LINQ data providers (such as: LINQ to Amazon, LINQ to Nhibernate, and LINQ to LDAP ).

Here I will discuss some of the new language features and improvements in C #3.0. They make LINQ so powerful that you can write suchCode:

 VaR result  =  From C  In  MERs
Where C. City = Boston "
Orderby C. lastname descending
Select New   {C. firstname, C. lastname, C. Address} ;

Remember, if you want to use LINQ, you need to install Visual Studio 2008 (. net3.5 ).

New language features

I/automatic attributes

 Public     Class  Point {
Private   Int _ X, _ y;
Public   Int X {
Get { Return _ X ;}
Set {_ X = Value ;}
}
Public   Int Y {
Get { Return _ Y ;}
Set {_ Y = Value ;}
}
}

The code above defines a class with two attributes. Now, using the C # compiler in vs2008, we can use automatic attributes to write more easily. It can automatically generate private domains with get/set operations.

  Public     class   point {
Public int X { Get ; set ;}
Public int Y { Get ; set ;}
}

The above code is more readable and concise.
(This feature has nothing to do with LINQ)

II/local variable type

This feature is used to declare a local variable. Its specific type is inferred by an initialization expression. This is done through the VaR keyword (the people who use the scripting language should be familiar with it, but they actually have a lot of difference ). We can write the following code:

 VaR num  =     50  ;
VaR Str =   " Simple string " ;
VaR OBJ =   New Mytype ();
VAR numbers =   New   Int [] { 1 , 2 , 3 };
VaR DIC =   New Dictionary < Int , Mytype > ();

The compiler will generate the Il intermediate code, just as we have compiled the following code:

 Int  Num  =     50  ;
String Str =   " Simple string " ;
Mytype OBJ =   New Mytype ();
Int [] Numbers =   New   Int [] { 1 , 2 , 3 };
Dictionary < Int , Mytype > Dic =   New Dictionary < Int , Mytype > ();

Note that there is no non-type variable here, and the binding of the type is not postponed. The compiler automatically deduce and declare the type of a variable from the value assignment statement on the right. The VaR keyword is a strongly typed variable reference.

III/object initialization and set Initialization

We continue to use the above point class. Suppose we want an instance of this class, we will create an object and set its attributes, the code will be like this:

 
Point P= NewPoint ();
P.x= 0;
P. Y= 0;

Now, using object initialization can be rewritten like this:

Point P= NewPoint () {x= 0, Y= 0};

This feature can also be used on the set. Let's take a look at the following example:

 List points  =     New  List {
New Point {x =   2 , Y =   5 },
New Point {x =   1 , Y =   - 10 },
New Point {x =   3 , Y =   0 }
};

Note that the compiler will generate code that is longer than the above, and it calls the add () method in sequence to add elements to the set.

IV/anonymous type

This language feature allows us to define embedded types without explicitly defining a type. In other words, if we do not define a point class, we need to use a point object (that is, the type is anonymous ). We can use the object initialization syntax mentioned above, but we do not need to specify the type name:

 
VaR P= New{X= 0, Y= 2};

In vs2008, you can still use smart sensing. So if you continue to use the Variable P, you will get the list of attributes of this anonymous type.

V/lambda expressions

The anonymous method is introduced in C #2.0, allowing a code block to be written in the place where the delegate is required. The anonymous method provides a functionProgramThe language capability and syntax are concise. Lambda expressions provide a more concise syntax for writing anonymous methods. A Lambda expression is a list of parameters (which can be implicitly typed), followed by a => symbol, followed by an expression or a statement block.

As an example, we define a delegate type mydeleg:

 
DelegateR mydeleg (A Arg );

Then we can use the anonymous method:

 Mydeleg  <  Int  ,  Bool  >  Ispositive  =    Delegate  (  Int  Num ){
Return Num >   0 ;
};

We can also use a new Lambda expression to write:

 
Mydeleg<Int,Bool>Ispositive=Num=>Num> 0;

VI/Extension Method

The extension method allows you to extend an existing type and add its method without inheriting it or re-compiling it. Unlike the object write assistant method, the extension method can be a part of the object itself.

For example, if we want to verify whether a string is a valid email address, we can write a method, enter it as a string, and return true or false. Now we can use the extension method as follows:

Public     Static     Class  Myextensions {
Public   Static   Bool Isvalidemailaddress ( This   String S ){
RegEx =   New RegEx ( @" ^ [W-.] + @ ([w-] +.) + [w-] {2, 4} $ " );
Return RegEx. ismatch (s );
}
}

We define a static class with a static method. Note that the static method has a this keyword before the parameter type string, which tells the compiler that this special extension method will be added to the string type object. So we can call this member method in string:

   using   myextensions; 
string email = request. querystring [ " email " ];
If (email. isvalidemailaddress () {
//
}

It is worth noting that the use of system is the function of LINQ. extension methods (such as where (), orderby (), select (), sum (), and average () in the LINQ namespace, and define standard query operators, it can be used to query relational databases, XML, and any interface that implements ienumerable <t>.. Net object.

VII/query syntax

The query expression provides a language-integrated syntax for query, especially for relational and hierarchical query languages such as SQL and XQuery. It is very convenient to write a query using the LINQ operator (that is, from... where... select). Visual Studio provides it with intelligent awareness and compiler check support.
When the C # compiler encounters a query syntax expression, it is actually converted to a method call using the extension method and Lambda expression.

Let's take an example to explain this:

VaR result=From CInMERs
WhereC. City. startswith ("B")
Orderby C. lastname
SelectNew{C. firstname, C. lastname, C. Address };

The above code is equivalent:

VaR result  =  Customers. Where (C  =>  C. City. startswith (  "  B  "  ))
. Orderby (C => C. lastname)
. Select (C =>   New {C. firstname, C. lastname, C. Address });

The benefit of using the query syntax is that it makes the code simpler and easier to read.
Note that the query expression starts with "from" and ends with "select" or "group.

Last note

Most of the features introduced in C #3.0 are just "compiler skills" or "syntactic sugar". In fact, the Il intermediate code generated by the compiler is the same as the original one, in this way, they are independent of the framework and CLR runtime. However, they do need the support of some frameworks, such as the system. Core. dll assembly. This is why the extension method still depends on the system. runtime. compilerservices. extensionattribute contained in system. Core. dll.
On the other hand, the query expression only implements the ing to the extension method, which is included in the namespace of system. LINQ, system. Data. LINQ, and system. xml. LINQ.

References and resources

  • "New orcas language feature" series by Scott Guthrie: Describes the LINQ SeriesArticle
  • LINQ resources: logs written by Daniel moth
  • Msdn magazine (June 2007): an article about C #3.0 and LINQ
  • Visual Studio orcas samples: C #/vB LINQ example
  • Future versions: C #3.0
  • The LINQ project: home page of the LINQ Project

     

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