To make the query syntax of Linq closer to C # and VB. NET, C #3.0, and VB. NET 9.0-based templates, anonymous methods, and iterators are important components of LINQ, including the following important features:
1. Hide local variables of the type
C #3.0 provides a new key sub-var, so that programmers do not need to clearly define a local variable, but the compiler initializes the variable according to the expression. For example, var name = "Linq"; with this feature, you no longer need to repeat the type of local variables. The Compiler automatically pushes the type and supports strong types. Besides, you can define the iterator type in the foreach loop.
2. object initialization program
This feature allows us to assign values to corresponding fields and attributes when the object is defined. For example:
Class Person
{
......
Public string Name {get; set ;}
Public int Age {get; set ;}
Public string Nation {get; set ;}
......
}
With this feature, you can initialize the variable in a declaration statement.
Var linq = new Person {Name = "Linq", Age = "2", Nation = "USA "};
The same is true for collections:
......
Var linqs = new List <Person> [] {
New Person {Name = "Linq to SQL", Age = 1, Nation = "USA "},
New Person {Name = "Linq to XML", Age = 2, Nation = "UK "},
New Person {Name = "Linq to DataSet", Age = 3, Nation = "GR "}
};
......
It is similar to adding an object using the Add method. However, you must note that the IEnumerable interface and the class that provides the Add method must be implemented.
3. Lambda expressions
Linq => linq. Age = 2
(Input parameter) (operator) (expression or declaration module)
If no parameter type is defined, the input parameter is of the hidden type. Of course, you can define specific types, such as (Person linq)
4. Extension Method
In fact, the simplest implementation is to add the this keyword before the first parameter. This keyword indicates that the compiler treats this method as an extension method. But the extension method must be declared in a non-template static class.
5. Anonymous class
In fact, the anonymous class only has no type name, and the actual type is determined by the compiler during creation. For example:
Var linq = new {"SQL to Object", 4, "CN "};
The advantage of this feature is that it can quickly return simple temporary results and facilitate development. But it also has its limitations. It is mainly because it cannot perform class operations in a strongly typed manner and cannot be used as the return value of a method (unless the return value of this method is of the Object type ). In addition, the anonymous class in C # is immutable, that is, once created, the attribute value cannot be changed.