Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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
Example:
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
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.
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)
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:
Task.Run
, lambda expressions can be used to define the asynchronous operation to be executed.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
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 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
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 {}
.
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
In this example, the lambda expression x => x * factor
captures the factor
variable from the enclosing scope.
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
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
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 expressions in C# are concise and expressive constructs that enable developers to write compact yet robust code by defining anonymous functions or delegates inline.
The syntax for a lambda expression is (parameters) => expression. For example, x => x * x is a lambda expression to square a number.
Lambda expressions are commonly used in LINQ queries, event handling, asynchronous programming, and functional programming to perform operations like filtering, mapping, and handling events.
Expression lambdas have a single expression and use the syntax x => x * x, while statement lambdas can have multiple statements enclosed in a block, such as (x) => { return x * x; }.
Yes, lambda expressions can capture variables from their enclosing scope, a feature known as variable capturing or closure, allowing them to access and use variables declared outside their body.
Lambda expressions can be used to perform operations like generating a list of squared numbers and rendering HTML content in C# applications.
A library can be installed in a C# application using the NuGet package manager with a command or through Visual Studio.
Lambda expressions make code more readable, maintainable, and efficient by allowing developers to define inline functions concisely, which enhances productivity and code elegance.