Lambda Expression in C# (With Examples)

Learn what lambda expressions are in C#, their syntax, and how they simplify writing concise, functional-style code with practical examples.

What is a Lambda Expression?

A lambda expression is a concise way to represent an anonymous method using the => (goes to) operator. It allows developers to write inline functions without formally defining a separate named method.

Basic Syntax

Lambda expressions follow the pattern (parameters) => expression or (parameters) => { statements }, letting you pass small pieces of logic directly wherever a delegate or function type is expected.

Using Lambdas with LINQ

Lambda expressions shine when combined with LINQ, enabling concise queries like list.Where(x => x > 10) that filter, transform, and aggregate collections in just a single readable line of code.

Lambdas with Delegates and Events

Beyond LINQ, lambda expressions are commonly used with delegates like Func and Action, as well as for wiring up event handlers quickly without cluttering the code with extra named methods.

Conclusion: Lambda expressions are a cornerstone of modern, functional-style C# programming. Mastering them unlocks cleaner, more expressive code, especially when working with LINQ and collection-based operations.

Lambdas in Code: Delegates You Will Use Daily

Think of the arrow as splitting the lambda into two halves: inputs on the left, the result or body on the right. The compiler checks both halves against the delegate it is being converted to, which is why parameter types can usually be left out.

A lambda has no type of its own until it is assigned to a delegate such as Func, Action or Predicate. The last type argument of Func is always the return type.

Func<int, int> square = x => x * x;                 // takes int, returns int
Func<int, int, int> add = (a, b) => a + b;          // two inputs
Action<string> greet = name => Console.WriteLine($"Hello, {name}");
Predicate<string> isEmpty = s => s.Length == 0;   // returns bool

// Statement lambda with a body
Func<double, string> grade = marks =>
{
    if (marks >= 75) return "Distinction";
    if (marks >= 40) return "Pass";
    return "Fail";
};

Console.WriteLine(square(6));    // 36
Console.WriteLine(add(3, 4));    // 7
greet("Priya");                  // Hello, Priya
Console.WriteLine(grade(81));    // Distinction

Newer C# versions can also infer a "natural type", so var parse = (string s) => int.Parse(s); compiles without spelling out the delegate.

Worked Example: Processing a Product List

LINQ methods accept lambdas for every step, so a whole report fits into a short, readable chain.

var products = new List<Product>
{
    new("Mouse", "Accessories", 499),
    new("Laptop", "Computers", 55999),
    new("Keyboard", "Accessories", 1299),
    new("Monitor", "Computers", 10999)
};

var report = products
    .Where(p => p.Price > 1000)
    .OrderByDescending(p => p.Price)
    .Select(p => $"{p.Name}: Rs {p.Price}");

foreach (var line in report) Console.WriteLine(line);

var totals = products
    .GroupBy(p => p.Category)
    .Select(g => new { Category = g.Key, Total = g.Sum(p => p.Price) });

record Product(string Name, string Category, decimal Price);

The first query prints Laptop, Monitor and Keyboard in price order. The second groups by category and adds prices inside each group. LINQ queries run lazily, so the filtering only happens when the foreach loop asks for items; calling ToList() runs the query once and stores the results.

Closures: Lambdas That Remember Variables

A lambda can use variables from the method around it. It captures the variable itself, not a copy of its value, so later changes are visible:

int threshold = 100;
Func<int, bool> isLarge = n => n > threshold;
threshold = 500;
Console.WriteLine(isLarge(300));   // False, because threshold is now 500

This is powerful, but it can surprise beginners inside for loops, where every lambda shares the same loop counter. Copy the counter into a local variable inside the loop when each lambda needs its own value. A foreach loop already gives each iteration a fresh variable.

Good Habits and Common Mistakes

  • Keep lambdas short. If a body grows beyond a few lines, move it into a named method and pass the method group instead.
  • Mark lambdas static when they capture nothing. Newer C# allows static x => x * 2, and the compiler then blocks accidental captures.
  • Use discards for unused parameters, as in button.Click += (_, _) => Save();.
  • Remember unsubscribing. An event handler written as an inline lambda cannot be removed later unless you keep a reference to it.
  • Know the database difference. When a lambda is passed as Expression<Func<T, bool>>, as in Entity Framework queries, it is translated to SQL, so calling your own C# helper methods inside it may fail at runtime.

Ready to Master C# Programming Course?

Join Uncodemy's hands-on training program with expert mentors and real-world projects.