⚡ Lambdas = Concise Functions
Anonymous methods are verbose. Lambda expressions are concise. One-liners for LINQ, delegates, events.
❌ Anonymous Method
Funcsquare = delegate(int x) { return x * x; };
✅ Lambda Expression
Funcsquare = x => x * x;
📝 Lambda Syntax
// Basic syntax
(parameters) => expression
(parameters) => { statements }
// Examples
x => x * x // Single parameter
(x, y) => x + y // Multiple parameters
() => DateTime.Now // No parameters
x => { return x * x; } // Statement lambda
// With LINQ
var adults = users.Where(u => u.Age >= 18);
var sorted = numbers.OrderBy(n => n);
var projected = users.Select(u => new { u.Name, u.Age });
var grouped = users.GroupBy(u => u.City);
// Event handlers
button.Click += (sender, e) =>
Console.WriteLine("Button clicked");
// Func and Action
Func add = (a, b) => a + b;
Action print = s => Console.WriteLine(s);
// Expression-bodied members
public string Name => firstName + " " + lastName;
public int Sum() => a + b;
// Multiple statements
Func calculate = x =>
{
var y = x * 2;
return y + 5;
};
// Discard parameter
button.Click += (_, _) => HandleClick();
// Tuple returns
Func getMultiplied = x => x switch
{
> 10 => x * 2,
> 5 => x * 3,
_ => x
};
🎯 Advanced Lambda Usage
// Closure int multiplier = 5; Funcmultiply = x => x * multiplier; // Chaining var result = numbers .Where(x => x > 0) .OrderBy(x => x) .Select(x => x * x) .ToList(); // Complex condition var filtered = items.Where(i => i.Active && i.Price > 100 && i.Category != "Deleted"); // Custom comparer var sorted = items.OrderBy(i => i.Name, (a, b) => a.Length.CompareTo(b.Length)); // Predicate with negation var adults = users.Where(u => !u.IsMinor); // Multiple conditions in LINQ var search = items.Where(i => (string.IsNullOrEmpty(searchTerm) || i.Name.Contains(searchTerm)) && (minPrice == null || i.Price >= minPrice) && (maxPrice == null || i.Price <= maxPrice) ); // Expression trees (for EF) Expression > filter = u => u.Age > 18; var query = db.Users.Where(filter);
💡 Lambda Best Practices
- Keep lambdas short and readable
- Use meaningful parameter names
- Use discard _ for unused parameters
- Avoid side effects in expressions
- Use with LINQ for readability
“Lambdas make code concise. Perfect for LINQ and events. Essential for modern C#.”
