What is Lambda Expression in C#: Simple Explanation and Example
lambda expression in C# is a short way to write an anonymous function using the => syntax. It lets you create quick, inline functions without naming them, often used with collections or delegates.How It Works
Think of a lambda expression as a quick recipe you write on a sticky note instead of a full cookbook. It lets you describe a small function right where you need it, without giving it a name. This is handy when you want to tell your program what to do with some data, like filtering or transforming a list, without creating a separate function elsewhere.
In C#, a lambda expression uses the => symbol to separate input parameters from the function body. For example, x => x * 2 means "take x and return x times 2." Behind the scenes, the compiler turns this into a delegate or expression tree that can be executed later.
Example
This example shows a lambda expression used to double each number in a list and print the results.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Use a lambda expression to double each number var doubled = numbers.Select(x => x * 2); foreach (var num in doubled) { Console.WriteLine(num); } } }
When to Use
Use lambda expressions when you need a quick, simple function without the overhead of writing a full method. They are perfect for working with collections, like filtering, sorting, or transforming data. For example, when you want to find all even numbers in a list or sort items by a property, lambdas make your code shorter and easier to read.
They are also useful when working with delegates, events, or LINQ queries, where you often pass small pieces of logic as arguments. This keeps your code clean and focused on what you want to do, not how to name every tiny function.
Key Points
- Lambda expressions are anonymous functions using
=>syntax. - They simplify writing inline functions, especially with collections and delegates.
- Commonly used with LINQ for filtering, selecting, and transforming data.
- They improve code readability by reducing boilerplate.