Lambda Expressions in C#: A Step-by-Step Guide
What is a Lambda expression in C#
Lambda expressions serve as a convenient feature in C# programming, enabling the creation of anonymous methods. They operate in conjunction with delegates, which are objects that represent a method. Utilizing lambda expressions can lead to more straightforward and streamlined code, enhancing readability and comprehension. Essentially, these expressions permit the construction of a function without the need for a separate method definition, resulting in more compact and effective code.
KEY TAKEAWAYS:
- Lambda expressions do not have a name and they are defined inline rather than being declared in a separate method.
- They often used in conjunction with delegates which are objects that represent a method. They can be used to pass methods as arguments to other methods which can be invoked at later time.
- Lambda expression in C# can be used to perform a variety of tasks, some common tasks that can be performed include filtering, sorting, and transforming data.
- Lambda expression C# can make code more readable and maintainable as they help us to reduce the amount of code.
- Lambda expressions in C# are a powerful feature that can be used to improve the code efficiency. And they help to avoid the need to create and call separate methods.
Delegates or expression tree types can be created, which is particularly useful when a quick function is needed for only use once or a few times in your application. Lambda expressions facilitate the writing of shorter and more expressive code, which is always beneficial.
For C# developers, acquiring expertise in lambda expressions is crucial for producing neat and efficient code. This Lambda Expressions tutorial will walk you through the syntax and usage of lambda expressions, delivering lucid explanations and practical examples throughout.
We encourage you to explore additional expert-level articles on this website to further understand how to write C# Lambda expressions with Lists, complex Functions, Async expressions, and more.
The Syntax of Lambda Expressions
When using a lambda expression, you have to separate its parameter list from its body using the declaration operator =>. The basic syntax for a lambda expression is as follows:
(input-parameters) => expression
You can omit the parentheses if there's only one input parameter:
input-parameter => expression
Getting Started with Lambda Expressions
Before diving into lambda expressions, make sure you have a suitable C# environment set up. You can use an integrated development environment (IDE) like Visual Studio or an online C# compiler like dotnetfiddle.net to write and test your code.
Step-by-Step: Writing Lambda Expressions:
-
Simple Lambda Expressions:
Let's start with a basic example. We'll create a lambda expression that takes a single integer parameter and returns its square:
Func<int, int> square = x => x * x;
Here, we define a delegate Func<int, int> takes an integer as input and returns an integer as its output. The lambda expression x => x * x specifies that the input parameter `x` should be squared. The lambda expression that is assigned to the “square” variable squares its input.
-
Lambda Expressions with Multiple Input Parameters:
Now, let's create a lambda expression with two input parameters. We'll write a lambda expression that adds two integers and returns the result:
Func<int, int, int> add = (x, y) => x + y;
In this case, we define a delegate Func<int, int, int> that takes two integers as input and returns an integer. The lambda expression (x, y) => x + y specifies that the input parameters `x` and `y` should be added together.
-
Lambda Expressions with Multiple Statements:
You can use the statement lambdas when you need to include multiple statements in your lambda expression. The syntax for a statement lambda is:
(input-parameters) => { statement; }
Here's an example of a statement lambda that calculates the product of two numbers and prints the result:
Action<int, int> multiplyAndPrint = (x, y) => { int result = x * y; Console.WriteLine($"The product of {x} and {y} is {result}"); };
Understanding Lambda Expression Types
There are two types of lambda expressions:
- Expression lambdas
- Statement lambdas
Expression lambdas consist of a single expression, while statement lambdas consist of one or more statements enclosed in curly braces. We've already seen examples of both types in the previous section.
Tips and Best Practices for Writing Lambda Expressions
- Keep your lambda expressions short and simple. If the logic becomes too complex, consider using a named method instead.
- Use meaningful parameter names to make your code more readable.
- Be cautious when using captured variables inside lambda expressions, as this can lead to unexpected behavior in certain situations.
Practice Exercises
To further solidify your understanding of lambda expressions, try working through the following exercises. Make sure to include required namespace before testing or practicing these code samples:
-
Write a lambda expression that takes two strings as input and returns the concatenated result.
Func<string, string, string> concatenate = (s1, s2) => s1 + s2;
-
Write a lambda expression that takes a double as input and returns its cube.
Func<double, double> cube = x => x * x * x;
-
Write a lambda expression that takes two integers as input and returns the larger one.
Func<int, int, int> max = (x, y) => x > y ? x : y;
-
Write a statement lambda that takes a string as input and prints it in uppercase.
Action<string> printUpperCase = s => { string upperCaseString = s.ToUpper(); Console.WriteLine(upperCaseString); };
Practice some advance Lambda Expressions in C# !
-
Switch in lambda expression:
This example uses “Recursive Pattern” feature of C# which is available in C# 8.0 or higher.
Func<int, string> switchInLambda = num => num switch { 1 => "One", 2 => "Two", _ => "Other" }; Console.WriteLine(switchInLambda(1)); // Output: One
-
Select in lambda expression (C#):
var numbers = new List<int> { 1, 2, 3 }; var squares = numbers.Select(n => n * n);
Select method with a lambda expression to compute square of each number in the list.
-
SelectMany in lambda expression (C#):
var listOfLists = new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } }; var flattened = listOfLists.SelectMany(l => l);
SelectMany method with a lambda expression to flatten a list of lists and get all values.
-
Distinct in lambda expression:
var numbers = new List<int> { 1, 2, 2, 3 }; var distinctNumbers = numbers.Distinct();
Distinct method to get the unique elements in the list.
-
Any in lambda expression:
var numbers = new List<int> { 1, 2, 3 }; bool hasEven = numbers.Any(n => n % 2 == 0);
Any method with a lambda expression to check if there is any even number in the list.
-
Async in lambda expression:
Func<Task> asyncLambda = async () => await Task.Delay(1000); await asyncLambda();
Async lambda expression that delays for 1 second and then invoke and await it.
-
Debug:
Debugging a lambda expression in C# is not much different than debugging any other piece of code. You can use following namespace and WriteLine method.
using System.Diagnostics; Debug.WriteLine("Debug message");
-
Lambda expression as parameter:
void ApplyFunc(int x, Func<int, int> func) => Console.WriteLine(func(x)); ApplyFunc(2, n => n * 2); // Output: 4
Here, we are passing a lambda expression as a parameter to a method.
-
Lambda expression to SQL query:
This requires a third-party library like Entity Framework or LINQ to SQL. Here's an example using Entity Framework:
using (var context = new MyDbContext()) { var result = context.Users.Where(u => u.Age >= 18).ToList(); }
The SQL query that will be generated by the C# compiler would look something like this:
SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[Age] AS [Age] FROM [dbo].[Users] AS [Extent1] WHERE [Extent1].[Age] >= 18
-
Return lambda expression:
Func<int, int> GetMultiplier(int factor) => n => n * factor; var doubler = GetMultiplier(2); Console.WriteLine(doubler(3)); // Output: 6
-
Include in lambda expression (using Entity Framework):
using (var context = new MyDbContext()) { var usersWithPosts = context.Users.Include(u => u.Posts).ToList(); }
In this example, we are using Include method with lambda expression to load related data (Posts) for each User.
-
Join in lambda expression:
var users = new List<User> { /* ... */ }; var orders = new List<Order> { /* ...*/ }; var userOrders = users.Join( orders, user => user.Id, order => order.UserId, (user, order) => new { user, order } ); foreach (var userOrder in userOrders) { Console.WriteLine($"User: {userOrder.user.Name}, Order: {userOrder.order.Id}"); }
Join method with lambda expressions to join two objects data in new anonymous type.
-
Where condition in Lambda expression:
var numbers = new List<int> { 1, 2, 3, 4, 5 }; var evenNumbers = numbers.Where(n => n % 2 == 0); foreach (int evenNumber in evenNumbers) { Console.WriteLine(evenNumber); // Output: 2, 4 }
Where method with a lambda expression to filter the even numbers in the list.
Conclusion
Lambda expressions are a powerful and concise way to represent anonymous functions in C# programming language. Mastering their syntax and usage can help you write cleaner and more efficient code. We hope this tutorial has provided you a solid understanding of lambda expressions in C#. Continue practicing and exploring their various use cases to further enhance your C# programming skills.
I encourage you to learn more about Lambda expressions and start using them in your own code. We have more articles and tutorials for Lambda expression in this website.