C# Advanced - Lambda
Posted on July 3, 2024 (Last modified on October 11, 2024) • 2 min read • 299 wordsVideo is in Swedish
Lambda expressions in C# are anonymous functions that can be used to simplify code and make it more readable. They were introduced in .NET Framework 3.0 and have been widely adopted since then.
A lambda expression is defined using the =>
operator, which separates the input parameters from the body of the function. The syntax for a lambda expression is as follows:
(input parameters) => { statements }
For example, consider the following code that calculates the sum of two numbers using a traditional method:
int x = 5;
int y = 10;
int result = x + y;
Console.WriteLine(result);
This can be rewritten using a lambda expression as follows:
int x = 5;
int y = 10;
int result = (x, y) => x + y;
Console.WriteLine(result);
In this example, the lambda expression takes two input parameters x
and y
, adds them together, and returns the result. The resulting value is then assigned to the variable result
.
Lambda expressions can also be used with LINQ (Language Integrated Query), which allows you to query data in a more intuitive way. For example, consider the following code that filters a list of integers based on a condition:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int targetNumber = 3;
var filteredNumbers = numbers.Where(n => n == targetNumber);
In this example, the lambda expression n => n == targetNumber
is used to filter the list of integers based on whether each number is equal to the targetNumber
. The resulting filtered list is then assigned to the variable filteredNumbers
.
Lambda expressions are a powerful feature in C# that can be used to simplify code and make it more readable. They are particularly useful when working with LINQ, as they allow you to write queries in a more intuitive way.
Swedish