C# lambda expression: simple and efficient code weapon
Although the Lambda expression of C# looks very similar to the anonymous method and the grammar is more concise, it provides a significant advantage.
Simplify the creation of anonymous commission
Lambda expression provides a more streamlined syntax to create anonymous commission. It can be used for any scene that can be entrusted anonymous.
The powerful features of expression trees and linq
Unlike anonymous entrustment, Lambda expression can be converted into an expression tree. This makes some powerful functions possible, such as Linq to SQL, which allows converting C# expression to SQL query to achieve seamless interaction with the database. Example: The improved linq grammar
The following code demonstrates the use of anonymous commission and lambda expression in Linq to Objects expressions, highlighting the readability of LAMBDA expression improvement:
Closed support
LAMBDA expression and anonymous commission support closure, allowing the local state to be passed to the function without additional parameters or disposable objects.
<code class="language-csharp">// 匿名委托 var evens = Enumerable.Range(1, 100).Where(delegate(int x) { return (x % 2) == 0; }).ToList(); // Lambda 表达式 var evens = Enumerable.Range(1, 100).Where(x => (x % 2) == 0).ToList();</code>
The advantages of the expression tree
Expressive tree provides a powerful mechanism to check the structure of the expression, not just the reference to the executable method. The API can make the entrusted parameter as an expression tree, so that the compiler can express the expression tree from Lambda rather than anonymous entrustment.Summary
LAMBDA expression combined with the function of the expression tree has a significant advantage over traditional methods and anonymous entrustment. Its simplified grammar, support for closing, and powerful functions of Linq make it an important tool in the C# developer tool package. Using Lambda expression can improve the readability, flexibility and efficiency of the code.
The above is the detailed content of Why Choose C# Lambda Expressions Over Anonymous Methods?. For more information, please follow other related articles on the PHP Chinese website!