Lambda expressions are a powerful feature in C# programming that allows you to write concise and efficient code. They provide a more expressive way of writing anonymous functions, making your code more readable and maintainable. In this article, we will explore how to use lambda expressions in C#.
In simple terms, a lambda expression is an anonymous function that can be used to create delegates or expression tree types. It provides a compact syntax to define a method on the fly without having to explicitly define a separate method.
The syntax of a lambda expression consists of three main parts: input parameter(s), lambda operator (=>
), and the expression or statement block.
(parameters) => expression/statement block
Here, parameters
represent the input parameters of the function, =>
denotes the link between the parameters and the function body, and the expression/statement block
represents the code to be executed.
Lambda expressions offer several benefits when used in C# programming:
Let's dive into some examples to understand how to use lambda expressions in C#:
// Lambda expression to calculate the square of a number
Func<int, int> square = num => num * num;
int result = square(5); // Output: 25
In this example, we define a lambda expression square
that takes an integer input num
and returns the square of that number. We assign this lambda expression to a Func<int, int>
delegate, allowing us to call it as a regular function.
// List of numbers
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Using lambda expression with LINQ to filter even numbers
var evenNumbers = numbers.Where(num => num % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
In this example, we use a lambda expression in conjunction with LINQ to filter even numbers from the given list. The lambda expression num => num % 2 == 0
is used as a predicate to filter the elements.
// List of students
List<Student> students = new List<Student>
{
new Student { Name = "Alice", Grade = 95 },
new Student { Name = "Bob", Grade = 85 },
new Student { Name = "Charlie", Grade = 92 }
};
// Sorting students by grade using lambda expression
var sortedStudents = students.OrderBy(student => student.Grade);
foreach (var student in sortedStudents)
{
Console.WriteLine($"{student.Name}: {student.Grade}");
}
In this example, we demonstrate how to use a lambda expression to sort a list of Student
objects based on their grades. The lambda expression student => student.Grade
is used as a key selector to determine the sorting order.
Lambda expressions are a powerful feature in C# that allows you to write succinct and expressive code. They offer various benefits such as code conciseness, reusability, and support for functional programming paradigms. By mastering the usage of lambda expressions, you can enhance your code quality and productivity in C# programming. So, go ahead and start leveraging the power of lambda expressions in your C# projects!
noob to master © copyleft