.NET HELP

C# Lambda Expressions (How It Works For Developers)

Published June 6, 2024
Share:

Introduction

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 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 operator oe method syntax
x=> x*x // expression to square a number
(parameters) => expression // lambda operator oe method syntax
x=> x*x // expression to square a number
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'(parameters) => expression x=> x*x ' expression to square a number
VB   C#

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 % 3 == 0);
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenNumbers = numbers.FindAll(x => x % 3 == 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 3 = 0)
VB   C#

In the above example, x => x % 3 == 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 array 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

The lambda expressions with => are called expression lambdas. They take the below 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
VB   C#

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's 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

The below code shows how to declare statement lambda expressions. Here a delegate is declared first which has a method with only parameters and body.

Then, when it is required, a function/method name is added to the delegate parameter.

Func<int> mySquareDelegate = (x =>
{
    return x*x;
});
Console.WriteLine(mySquareDelegate(4));
Func<int> mySquareDelegate = (x =>
{
    return x*x;
});
Console.WriteLine(mySquareDelegate(4));
Dim mySquareDelegate As Func(Of Integer) = (Function(x)
	Return x*x
End Function)
Console.WriteLine(mySquareDelegate(4))
VB   C#

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
VB   C#

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
VB   C#

IronPDF a PDF library from Iron Software

IronPDF is 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.

namespace IronPatterns;
class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        var renderer = new ChromePdfRenderer(); // var pattern
        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 };
        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);
        pdf.SaveAs("output.pdf"); // Saves PDF
    }
}
namespace IronPatterns;
class Program
{
    static void Main()
    {
        Console.WriteLine("-----------Iron Software-------------");
        var renderer = new ChromePdfRenderer(); // var pattern
        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 };
        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);
        pdf.SaveAs("output.pdf"); // Saves PDF
    }
}
Namespace IronPatterns
	Friend Class Program
		Shared Sub Main()
			Console.WriteLine("-----------Iron Software-------------")
			Dim renderer = New ChromePdfRenderer() ' var pattern
			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}
			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)
			pdf.SaveAs("output.pdf") ' Saves PDF
		End Sub
	End Class
End Namespace
VB   C#

Output

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

Trial License

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

"IronPDF.LicenseKey": "<Your Key>"

Place the License key in the AppSettings.Json file.

Conclusion

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!

< PREVIOUS
C# Catch Multiple Exceptions (How It Works For Developers)
NEXT >
Internal Keyword C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >