跳過到頁腳內容
.NET幫助

C# Lambda Expressions(對於開發者的運行原理)

In the realm of C# programming, lambda expressions stand as one of the most powerful features. These concise and expressive constructs enable developers to write compact yet robust code, enhancing readability, maintainability, and overall efficiency.

In this article, we'll dive deep into C# lambda expressions, exploring their syntax, use cases, benefits, and advanced techniques. We will also be exploring how IronPDF's capabilities from Iron Software can generate a PDF document on the fly in C# applications.

Understanding Lambda Expressions

Lambda expressions, introduced in C# 3.0, provide a succinct way to define anonymous functions or delegates. They are essentially inline anonymous functions that can be used wherever a delegate type is expected.

The syntax for a lambda expression is:

(parameters) => expression // lambda expression syntax
(parameters) => expression // lambda expression syntax
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'(parameters) => expression ' lambda expression syntax
$vbLabelText   $csharpLabel

例:

x => x * x // lambda expression to square a number
x => x * x // lambda expression to square a number
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'x => x * x ' lambda expression to square a number
$vbLabelText   $csharpLabel

Here, parameters are the input parameters of the lambda expression, and expression is the statement or block of statements to be executed. The .NET common language runtime creates an anonymous function for each lambda expression during compile time.

Basic Usage

Let's look into an example for Lambda expression where we have a list of integers, and we want to filter out the even numbers.

We can achieve this using the List<T>.FindAll method along with a lambda expression:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenNumbers = numbers.FindAll(x => x % 2 == 0);
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenNumbers = numbers.FindAll(x => x % 2 == 0);
Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim evenNumbers As List(Of Integer) = numbers.FindAll(Function(x) x Mod 2 = 0)
$vbLabelText   $csharpLabel

In the above example, x => x % 2 == 0 is a lambda expression that takes an integer x as an input parameter and returns true if x is even, and false otherwise. The lambda body expression is executed on each list element.

Use Cases

Using a Lambda expression in modern application programming finds a variety of use cases, including:

  1. LINQ Queries: Lambda expressions are extensively used in LINQ (Language Integrated Query) to perform filtering, projection, sorting, and grouping operations on data collections.
  2. Event Handling: When working with events and delegates, lambda expressions provide a concise way to define event handlers inline.
  3. Asynchronous Programming: In asynchronous programming patterns like Task.Run, lambda expressions can be used to define the asynchronous operation to be executed.
  4. Functional Programming: Lambda expressions support functional programming paradigms, enabling operations like map, filter, and reduce on collections.

Types of Lambda expressions

Expression Lambdas

Lambda expressions with => are called expression lambdas. They take the format:

x => x * x // expression to square a number
x => x * x // expression to square a number
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'x => x * x ' expression to square a number
$vbLabelText   $csharpLabel

In the above example, we are creating a square of a number. In expression lambdas, the body can include method calls. However, when generating expression trees intended for evaluation outside the .NET Common Language Runtime (CLR), such as in SQL Server, it is advisable to avoid any method call within lambda expressions.

This is because methods may lack meaning outside the CLR context. Therefore, it's crucial to consider the target environment when constructing an expression tree to ensure compatibility and meaningful interpretation.

Statement Lambdas

Statement lambda expressions allow multiple statements and provide more complex operations:

Func<int, int> mySquareDelegate = (x) =>
{
    return x * x;
};

Console.WriteLine(mySquareDelegate(4)); // Output: 16
Func<int, int> mySquareDelegate = (x) =>
{
    return x * x;
};

Console.WriteLine(mySquareDelegate(4)); // Output: 16
Dim mySquareDelegate As Func(Of Integer, Integer) = Function(x)
	Return x * x
End Function

Console.WriteLine(mySquareDelegate(4)) ' Output: 16
$vbLabelText   $csharpLabel

In this code, a delegate is declared that operates on integers and returns their square. The lambda body can encompass multiple statements inside a block {}.

Advanced Techniques

Capturing Variables

Lambda expressions can capture variables from the enclosing scope. This feature, known as variable capturing or closure, allows lambda expressions to access and use variables declared outside their body:

int factor = 2;
Func<int, int> multiplier = x => x * factor;
int factor = 2;
Func<int, int> multiplier = x => x * factor;
Dim factor As Integer = 2
Dim multiplier As Func(Of Integer, Integer) = Function(x) x * factor
$vbLabelText   $csharpLabel

In this example, the lambda expression x => x * factor captures the factor variable from the enclosing scope.

Multiple Parameters and Statements

Lambda expressions can have more than one parameter and execute multiple statements enclosed in a block:

Func<int, int, int> add = (a, b) =>
{
    int result = a + b;
    Console.WriteLine($"The sum of {a} and {b} is {result}");
    return result;
};
Func<int, int, int> add = (a, b) =>
{
    int result = a + b;
    Console.WriteLine($"The sum of {a} and {b} is {result}");
    return result;
};
Dim add As Func(Of Integer, Integer, Integer) = Function(a, b)
	Dim result As Integer = a + b
	Console.WriteLine($"The sum of {a} and {b} is {result}")
	Return result
End Function
$vbLabelText   $csharpLabel

IronPDF: A PDF library from Iron Software

Explore IronPDF as a versatile and high-performing PDF generation and parsing library from Iron Software which can be used to generate PDF Documents.

IronPDF can be installed from the NuGet package manager with the below command:

Install-Package IronPdf

Or installed from Visual Studio as shown below:

C# Lambda Expressions (How It Works For Developers): Figure 1 - Installing IronPDF with the NuGet package manager

Now let's dive into PDF generation using a lambda expression:

using IronPdf; // Import the IronPdf library
using System;
using System.Collections.Generic;
using System.Linq;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // Initialize the PDF renderer
            var content = "<h1> Iron Software is Awesome </h1> Made with IronPDF!";
            content += "<h2>Demo C# lambda expressions</h2>";
            content += $"<p>Generating Square of list of numbers x=>x*x</p>";

            List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            // Use Select to create a list of squared numbers
            List<int> squares = numbers.Select(x => x * x).ToList();

            content += $"<p>Numbers list: {string.Join(",", numbers)}</p>";
            content += $"<p>Squares: {string.Join(",", squares)}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content); // Render the HTML as a PDF
            pdf.SaveAs("output.pdf"); // Save the PDF document
        }
    }
}
using IronPdf; // Import the IronPdf library
using System;
using System.Collections.Generic;
using System.Linq;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // Initialize the PDF renderer
            var content = "<h1> Iron Software is Awesome </h1> Made with IronPDF!";
            content += "<h2>Demo C# lambda expressions</h2>";
            content += $"<p>Generating Square of list of numbers x=>x*x</p>";

            List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            // Use Select to create a list of squared numbers
            List<int> squares = numbers.Select(x => x * x).ToList();

            content += $"<p>Numbers list: {string.Join(",", numbers)}</p>";
            content += $"<p>Squares: {string.Join(",", squares)}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content); // Render the HTML as a PDF
            pdf.SaveAs("output.pdf"); // Save the PDF document
        }
    }
}
Imports IronPdf ' Import the IronPdf library
Imports System
Imports System.Collections.Generic
Imports System.Linq

Namespace IronPatterns
	Friend Class Program
		Shared Sub Main()
			Console.WriteLine("-----------Iron Software-------------")
			Dim renderer = New ChromePdfRenderer() ' Initialize the PDF renderer
			Dim content = "<h1> Iron Software is Awesome </h1> Made with IronPDF!"
			content &= "<h2>Demo C# lambda expressions</h2>"
			content &= $"<p>Generating Square of list of numbers x=>x*x</p>"

			Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
			' Use Select to create a list of squared numbers
			Dim squares As List(Of Integer) = numbers.Select(Function(x) x * x).ToList()

			content &= $"<p>Numbers list: {String.Join(",", numbers)}</p>"
			content &= $"<p>Squares: {String.Join(",", squares)}</p>"

			Dim pdf = renderer.RenderHtmlAsPdf(content) ' Render the HTML as a PDF
			pdf.SaveAs("output.pdf") ' Save the PDF document
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

輸出

C# Lambda Expressions (How It Works For Developers): Figure 2

Trial License

IronPDF code can run only with a trial license obtained from the IronPDF trial license page. Provide an Email ID in the pop-up to generate a license key and deliver that key to your email.

"IronPDF.LicenseKey": "<YourKey>"

Place the License key in the AppSettings.json file.

結論

C# lambda expressions offer a concise and expressive way to define inline functions, making code more readable, maintainable, and efficient. They find applications in various domains, including LINQ queries, event handling, asynchronous programming, and functional programming.

By mastering lambda expressions, developers can unlock new dimensions of productivity and elegance in their C# codebases.

Whether you're a seasoned C# developer or just starting your journey, understanding and harnessing the power of lambda expressions will undoubtedly elevate your programming skills to new heights.

So dive in, experiment, and embrace the beauty of lambda expressions in your C# projects!

常見問題解答

我如何使用 Lambda 表達式生成 C# 中的 PDF?

當使用 IronPDF 以程式化方式生成 PDF 時,您可以使用 Lambda 表達式來簡化代碼。例如,您可以使用 Lambda 來在使用 IronPDF 方法將數據渲染到 PDF 文檔之前對其進行過濾。

Lambda 表達式在 LINQ 查詢中的重要性是什麼?

Lambda 表達式在 LINQ 查詢中發揮著至關重要的作用,因為它提供了一種簡潔的方法來定義過濾、排序和投影數據等操作的功能。這提高了 C# 中 LINQ 查詢的可讀性和效率。

Lambda 表達式如何增強 C# 中的異步編程?

Lambda 表達式通過允許開發人員內聯定義回調函數來簡化異步編程。這對於事件驅動編程和處理異步任務尤為有用,能夠使代碼更加可讀和可維護。

C# 應用程式中是否可以在事件處理中使用 Lambda 表達式?

是的,Lambda 表達式通常用於事件處理,因為它們允許以簡潔的方式定義事件處理程序。這樣可以使代碼更加清晰和直觀,尤其是在使用像 IronPDF 這樣的庫處理文檔事件時。

C# 中表達式 Lambda 和語句 Lambda 之間有何區別?

表達式 Lambda 由單一表達式組成,使用語法 x => x * x,而語句 Lambda 可以在一個塊內包含多個語句,使用語法 (x) => { return x * x; }。此區別使開發人員能夠根據函數的複雜性做出選擇。

變量捕獲如何增強 Lambda 表達式的功能?

Lambda 表達式可以從其封閉範圍捕獲變量,這一功能稱為變量捕獲或閉包。這使它們能夠訪問並使用外部變數,從而在 C# 中實現更動態和靈活的函數定義。

使用多個參數的 Lambda 表達式有什麼高級技巧?

Lambda 表達式可以通過在括號中用逗號分隔多個參數來處理多個參數。這種靈活性使開發人員能夠內聯定義複雜的功能,這可以在高級編程場景中發揮作用,例如使用 IronPDF 生成複雜的 PDF 文檔。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。