C# Lambda Expressions(對於開發者的運行原理)
在 C# 程式設計領域中,lambda 表達式是最強大的功能之一。 這些簡潔且具表達力的構成方式,可讓開發人員寫出精簡但強大的程式碼,進而提升可讀性、可維護性和整體效率。
在這篇文章中,我們將深入探討 C# lambda 表達式,探索它們的語法、用例、優點和進階技術。 我們也將探討 Iron Software 的 IronPDF 的功能如何在 C# 應用程式中即時產生 PDF 文件。
瞭解 Lambda 表示式。
在 C# 3.0 中引入的 Lambda 表達式提供了定義匿名函數或委託的簡潔方式。 它們基本上是內嵌的匿名函數,可以用在任何需要委託類型的地方。
lambda 表達式的語法為
(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
範例:
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
這裡,parameters 是 lambda 表達式的輸入參數,而 expression 是要執行的語句或語句區塊。 .NET 常用語言執行時間會在編譯期間為每個 lambda 表達式建立一個匿名函式。
基本用法
讓我們來看看 Lambda 表達式的範例:我們有一個整數清單,想要篩選出偶數。
我們可以使用 List<t>.FindAll 方法以及 lambda 表達式來實現這一點:
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)
在上面的例子中,x => x % 2 == 0 是一個 lambda 表達式,它接受一個整數 x 作為輸入參數,如果 x 為偶數,則返回 `@ false。 lambda 表達式的主體部分會對列表中的每個元素執行。
使用案例
在現代應用程式編程中使用 Lambda 表達式可找到多種用例,包括
- LINQ 查詢: Lambda 運算式在 LINQ(語言整合查詢)中被廣泛使用,用於對資料集合執行篩選、投影、排序和分組運算。 2.事件處理:在使用事件和委託時,lambda 表達式提供了一種簡潔的方式來內嵌定義事件處理程序。 3.非同步程式設計:在非同步程式設計模式中,可以使用 lambda 表達式定義要執行的非同步操作。 4.函數式程式設計: Lambda 表達式支援函數式程式設計範式,可以對集合執行 map、filter 和 reduce 等運算。
Lambda 表達式的類型
表達式λ
帶有 => 的 Lambda 表達式稱為表達式 lambda。 他們採取的格式是
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
在上面的例子中,我們正在建立一個數字的平方。 在表達式 lambdas 中,正文可以包含方法呼叫。 但是,當產生要在 .NET Common Language Runtime (CLR) 以外(例如在 SQL Server 中)進行評估的表達式樹時,建議避免在 lambda 表達式中進行任何方法呼叫。
這是因為方法在 CLR 上下文之外可能會缺乏意義。 因此,在構建表達樹時,考慮目標環境以確保相容性和有意義的詮釋是至關重要的。
語句λ
語句 lambda 表達式允許多重語句,並提供更複雜的操作:
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
在此程式碼中,宣告了一個 delegate,可對整數進行操作並傳回其平方。 lambda 主體可以包含區塊內的多個語句 {}。
進階技術
擷取變數
Lambda 表達式可以捕捉圍繞作用域的變數。 此功能稱為變數擷取或封閉,允許 lambda 表達式存取和使用在其體外宣告的變數:
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
在這個例子中,lambda 表達式 x => x * factor 從封閉作用域中捕獲 factor 變數。
多重參數和語句
Lambda 表達式可以有一個以上的參數,並且可以在一個區塊中執行多個語句:
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
IronPDF:來自 Iron Software 的 PDF 函式庫。
探索 IronPDF 是 Iron Software 提供的多功能、高性能 PDF 生成和解析庫,可用於生成 PDF 文檔。
IronPDF 可從 NuGet 套件管理員中透過以下指令安裝:
Install-Package IronPdf
或從 Visual Studio 安裝,如下圖所示:

現在讓我們深入了解使用 lambda 表達式產生 PDF:
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
輸出

試用授權
只有從 IronPDF試用授權頁面取得試用授權,才能執行 IronPDF 程式碼。 在彈出式視窗中提供電子郵件 ID,以產生授權金鑰,並將該金鑰傳送至您的電子郵件。
"IronPdf.LicenseKey": "<YourKey>"
將許可證金鑰放入 AppSettings.json 文件中。
結論
C# lambda 表達式提供簡潔且具表達力的方式來定義內嵌函數,讓程式碼更具可讀性、可維護性及效率。 這些工具可應用於各種領域,包括 LINQ 查詢、事件處理、異步程式設計和函式程式設計。
透過掌握 lambda 表達式,開發人員可以在他們的 C# 程式碼庫中釋放出新的生產力與優雅性。
無論您是經驗豐富的 C# 開發人員,或是才剛開始您的旅程,了解並運用 lambda 表達式的力量,無疑會讓您的程式設計技巧提升到新的高度。
因此,請投入、嘗試,並在您的 C# 專案中擁抱 lambda 表達式之美!
常見問題解答
我如何使用 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 文件。



