Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views2 pages

Csharp Lambda Expressions Professional

Uploaded by

SanjeevSonu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Csharp Lambda Expressions Professional

Uploaded by

SanjeevSonu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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);

You might also like