Based on the generic type, the generic type is introduced in. NET Framework 2.0. You do not need to know more about generics to write queries. However, you may need to understand two basic concepts:
- When you create a generic collection class (such as list <(of <(T>), replace "T" with the type of the object contained in the list. For example, the string list is represented as list, and the customer Object List is represented as list. The generic list is strongly typed and provides more benefits than storing its elements as a collection of objects. If you try to add the customer to the list, an error occurs during compilation. The reason why generic collections are easy to use is that you do not have to perform forced type conversion during runtime.
- Ienumerable <(of <(T>)> Is an interface through which you can use foreach statements to enumerate generic collection classes. Generic collection classes support ienumerable <(of <(T>)>, just like non-generic collection classes (such as arraylist) Support ienumerable.
Ienumerable variable in the LINQ Query
The LINQ query variable is of the ienumerable <(of <(T>)> or derived type, such as iqueryable <(of <(T>)> ). When you see the query variable converted to ienumerable, this only means that when the query is executed, the query will generate a sequence containing zero or multiple customer objects.
Ienumerable <customer> customerquery =
From Cust in mers MERs
Where Cust. City = "London"
Select Cust;
Foreach (customer in customerquery)
{
Console. writeline (customer. lastname + "," + customer. firstname );
}
Let the compiler handle generic type declarations
If you want to, you can use the VaR keyword to avoid using the generic syntax. The VaR keyword indicates that the compiler can infer the type of the query variable by viewing the data source specified in the from clause. The following example generates the same compilation code as the previous example:
VaR customerquery2 =
From Cust in mers MERs
Where Cust. City = "London"
Select Cust;
Foreach (VAR customer in customerquery2)
{
Console. writeline (customer. lastname + "," + customer. firstname );
}
The VaR keyword is useful when the variable type explicitly or explicitly specifies the nested generic type (such as those generated by the group query) is not important. Generally, we recommend that you use VaR to realize that this may make your code harder for others to understand.