Lambda Expressions in C#
A **lambda expression** is an **anonymous method** in C#. It has no access modifier, no name, and
often no explicit return statement. Lambda expressions make code **shorter, cleaner, and more
readable**.
Why Use Lambda Expressions?
- Less code, more concise. - Improves readability. - Useful with delegates and LINQ queries.
Basic Example
Traditional method to calculate square:
static int Square(int number)
{
return number * number;
}
Console.WriteLine(Square(5)); // 25
Lambda version
Lambda equivalent of Square method:
Func<int, int> square = number => number * number;
Console.WriteLine(square(5)); // 25
Delegates Refresher
- **Func** → Method with input(s) and return value. - **Action** → Method with input(s), no return. -
**Predicate** → Method with one input, returns bool.
Closures Example
Lambdas can access variables outside their scope:
int factor = 5;
Func<int, int> multiplier = n => n * factor;
Console.WriteLine(multiplier(10)); // 50
Practical Example: Book Repository
Filtering with and without lambda expressions.
class Book { public string Title; public int Price; }
class BookRepository
{
public List<Book> GetBooks()
{
return new List<Book>
{
new Book { Title = "Title1", Price = 5 },
new Book { Title = "Title2", Price = 7 },
new Book { Title = "Title3", Price = 17 }
};
}
}
// Without Lambda
List<Book> cheapBooks = books.FindAll(IsCheaperThan10Dollars);
// With Lambda
List<Book> cheapBooks = books.FindAll(b => b.Price < 10);