How does. Net implement LINQ ~,. Net
Content
- Introduction
- Two prerequisites for implementing LINQ
- Extension Method
- Lambda expression
- LINQ
- References
This article describes how to implement LINQ. Only by knowing this can we better use it ~
If you are new to LINQ, you may not understand it as soon as possible. Because of the many technologies involved in LINQ, it can be said that it is a collection of many technologies, so using LINQ requires you to have a certain understanding of several knowledge points, this includes generic delegation, extension methods, anonymous functions, and Lambda expressions. On this basis, it is possible to use LINQ flexibly. This is also why the emergence of LINQ in VS 2008, rather than before.
It is best to first learn generic delegation and then learnSystem. ArrayClass to improve understanding of anonymous functions and lambda expressions.
Download Demo Introduction
If you have an F1 racing championRacer,RacerIncluding the name, country, number of champions, and other attributes of the contestant. To perform operations on this set, such as search and sorting, before C #3.0, the Code is as follows:
IEnumerable<Racer> brazilChampions = champions.Where(
delegate(Racer r)
{
return r.Country == "Brazil";
}).OrderByDescending(
delegate(Racer r)
{
return r.Wins;
}).Select(
delegate(Racer r)
{
return r;
});
Where,ChampionsIs a set of champions.
Note:Where,OrderByDescending,SelectAll functions use delegation as function parameters. The chained call will return an availableForeachStatement IterationIEnumerableEnumerated objectsBrazilChampions.
Although the above Code looks okay, but there areDelegateKeywords and formal parameters are not concise enough. Is it possible to have nothing to worry about? You probably think of the -- Lambda expression! The Code is as follows:
IEnumerable<Racer> brazilChampions = champions.
Where(r => r.Country == "Brazil").
OrderByDescending(r => r.Wins).
Select(r => r);
Well, it's much more concise ~ But we thought again, since it is a query, can we write an SQL statement like a database query? For example:Select * from champions t where t. country = "Brazil" orderby descOr similar form. SQL statements contain predicates ~
Of course, this is the result ~
However, it does not come out of the way. It has a process, which is why it appears in VS 2008, rather than before.
To better use it, learn how to implement LINQ ~
Two prerequisites for implementing LINQ
To understand how LINQ is implemented, you need to know two necessary technical points: the extension method and the lambda expression. Generic delegation is also involved.
Extension Method
In fact, the extension method is no stranger. For the first time, I noticed that this method is used in Ext. Net. It has a tool assembly in its project. The string tool classStringUtilsFor example, to determine whether the string is "null", whether it is null or the length is 0, true is returned to extend the. Net string operation. As shown belowStringUtilsTool code snippet:
public static class StringUtils
{
/// <summary>
/// Determine is the string is null or empty.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsEmpty(this string text)
{
return string.IsNullOrEmpty(text);
}
/// <summary>
/// Determine is the string is NOT null or empty.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsNotEmpty(this string text)
{
return !text.IsEmpty();
}
……
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static bool Test(this string text, string pattern)
{
return Regex.IsMatch(text, pattern);
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="pattern"></param>
/// <param name="options"></param>
/// <returns></returns>
public static bool Test(this string text, string pattern, RegexOptions options)
{
return Regex.IsMatch(text, pattern, options);
}
……
}
Apparently,. Net does not provideIsEmptyAndTestMethod (in fact,. Net providesString. IsNullOrEmptyMethod), but if you define this class in your program set, you can use "." To directly call these methods in your code, such"Helloworld". IsEmpty ().
Note,StringUtilsIs a static class. Static classes are mainly for sharing, and the members of static classes must also be static. Static classes are generally constructed during program loading. Static classes can have constructors, but they are called only once. In this way, you do not need to instantiate this class in your code. More importantly, for function parametersStringType UsedThisKeyword.
Because all generic sets inheritIEnumerable <T>Interface,In this way, we can customize the filter function.WhereIEnumerable <T>Use the extension method. As shown in the following figure, a generic set returns a set that meets the specified conditions:
public static IEnumerable<T> Where(this IEnumerable<T> source, Func<T, bool> predicate)
{
foreach (T item in source)
{
if (predicate(item))
yield return item;
}
}
Among them, the functionWhereThere are two parameters:ThisOfIEnumerable <T>. Net provides only two input parameters with the returned value generic delegation.Func <T, TResult>. In this way, calling the Where Method for any generic set is equivalent:
champions.Where(Func<T, bool> predicate)
For example:
IEnumerable<Racer> brazilChampions = champions.Where(
delegate(Racer r)
{
return r.Country == "Brazil";
});
Since the custom generic setWhereMethod returnedIEnumerable <T>Type. Of course, we can define another sorting function for a generic set, suchOrderByDescending (this IEnumerable <T> source, Func <T, int> predicate).
Because user-defined functionsWhereIs also a function.OrderByDescendingSo they can form a call chain.
Lambda expression
C #3.0 introduces a new syntax-Lambda expressions ). There is a mathematical foundation behind the lambda algorithm. That is to say, function declarations, including function names, form parameters, and return types, can all be absent and direct function bodies. The customWhereYou can write a function as follows:
IEnumerable<Racer> brazilChampions = champions.Where(r => r.Country == "Brazil");
Where,RNot defined. This code is much more concise.
The extension method and the lambda expression are mentioned earlier, and now they are close to the LINQ.
LINQ
We hope that, like SQLSelect, where, group by, orderThe compiler only needs to map these keywords to the corresponding extension method.
However, the keyword of LINQ is similar to that of SQL, for exampleFrom, where, orderby, descending, and select.
The above generic query is changed to LINQ as follows:
var query = from r in champions
where r.Country == "Brazil"
orderby r.Wins descending
select r;
Where,
where r.Country == "Brazil"
Convert
Where(r=>r.country=="Brazil");
orderby r.Wins descending
Convert
OrderByDescending(r=>r.Wins)
select r
Convert
Select()
TheFromClauseSelectOrGroupClause ends. You can useWhere,Orderby,JionAnd othersFromClause.
You have to study the specific usage of LINQ on your own. It is not covered in this article ~
References
- . Net c # declaration, instantiation and use of delegation and the Development of delegation in C #
- There is no Lambda Algorithm for how to use anonymous functions-Anonymous functions (anonymous methods and Lambda), delegation, and LINQ
- Wiki Lambda Algorithm
- Database SQL Language Reference
- . NET Framework System. Array. Sort demo
Download Demo