.NETヘルプ C# Lambda Expressions(開発者向けの動作方法) Curtis Chau 更新日:7月 28, 2025 Download IronPDF NuGet Download テキストの検索と置換 テキストと画像のスタンプ Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 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. 使用例 Using a Lambda expression in modern application programming finds a variety of use cases, including: LINQ Queries: Lambda expressions are extensively used in LINQ (Language Integrated Query) to perform filtering, projection, sorting, and grouping operations on data collections. Event Handling: When working with events and delegates, lambda expressions provide a concise way to define event handlers inline. Asynchronous Programming: In asynchronous programming patterns like Task.Run, lambda expressions can be used to define the asynchronous operation to be executed. 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: 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 出力 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! よくある質問 C#でPDFを生成するためにラムダ式をどのように使用できますか? ラムダ式を使用してコードを簡略化し、IronPDFと共にプログラムでPDFを生成することができます。例えば、データをフィルタリングしてからIronPDFのメソッドを使用してPDFドキュメントにレンダリングする前にラムダを使用することができます。 LINQクエリにおけるラムダ式の重要性は何ですか? ラムダ式は、フィルタリング、ソート、投影データなどの操作のための関数を簡潔に定義することでLINQクエリにおいて重要な役割を果たします。これにより、C#におけるLINQクエリの可読性と効率性が向上します。 C#における非同期プログラミングをどのようにラムダ式が向上させますか? ラムダ式は、開発者がコールバック関数をインラインで定義できるようにすることで非同期プログラミングを簡素化します。これは特にイベント駆動プログラミングや非同期タスクの処理において、コードをより読みやすく、維持しやすくするのに役立ちます。 C#アプリケーションでのイベントハンドリングにラムダ式を利用できますか? はい、ラムダ式はイベントハンドリングでよく使用されます。これにより、イベントハンドラを簡潔に定義でき、コードをよりクリーンで直感的にすることができます。特にIronPDFのようなライブラリを使用してドキュメントイベントを処理する際に便利です。 C#における式ラムダとステートメントラムダの違いは何ですか? 式ラムダは単一の式で成り立ち、x => x * xという構文を使用しますが、ステートメントラムダは複数の文をブロック内に含めることができ、(x) => { return x * x; }という構文を使用します。この違いにより、開発者は関数の複雑さに応じて選択できます。 変数キャプチャはラムダ式の機能をどのように向上させますか? ラムダ式は、囲むスコープから変数をキャプチャすることができ、これを変数キャプチャまたはクロージャと呼びます。これにより、外部の変数にアクセスして、より動的で柔軟な関数定義が可能になります。 複数のパラメータを持つラムダ式を使用するための高度な技術は何ですか? ラムダ式は、カンマで区切って複数のパラメータを処理できます。この柔軟性により、開発者は、インラインで複雑な関数を定義でき、IronPDFを使用して複雑なPDFドキュメントを生成するなどの高度なプログラミングシナリオで活用されます。 Curtis Chau 今すぐエンジニアリングチームとチャット テクニカルライター Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。 関連する記事 更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む 更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む 更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む C# Catch Multiple Exceptions(開発者向けの動作方法)Internal Keyword C#(開発者向...
更新日 9月 4, 2025 RandomNumberGenerator C# RandomNumberGenerator C#クラスを使用すると、PDF生成および編集プロジェクトを次のレベルに引き上げることができます 詳しく読む
更新日 9月 4, 2025 C# String Equals(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む
更新日 8月 5, 2025 C# Switch Pattern Matching(開発者向けの仕組み) 強力なPDFライブラリであるIronPDFと組み合わせることで、switchパターンマッチングは、ドキュメント処理のためのよりスマートでクリーンなロジックを構築できます 詳しく読む