A C# lambda defines a function where it is needed. It is useful when an operation needs a decision or callback but a separate named method would add clutter. For example, a general product filter can accept a Func<Product?, bool> and call it for each product; the caller supplies the rule. section 5.10.1
Supply a filter rule
In HomeController, a price rule can be written as p => (p?.Price ?? 0) >= 20. Here p is the product, => reads “goes to,” and the expression produces the bool used by Filter. A different lambda can test whether a product name begins with S. The same Filter method then handles both totals without separate FilterByPrice and FilterByName methods. section 5.10 section 5.10.1
Choose the form that fits the callable:
- Let the parameter type be inferred when it is clear from the receiving function, as in p => EvaluateProduct(p). section 5.10.1
- Put multiple parameters in parentheses: (prod, count) => prod.Price > 20 && count > 0. section 5.10.1
- Use braces and an explicit return when the implementation needs multiple statements. section 5.10.1
The => syntax also gives single-statement constructors, methods, and properties an expression body. For example, a controller action can be written as Index() => View(Product.GetProducts().Select(p => p?.Name));. The action’s expression body replaces its usual return statement; the lambda inside Select chooses each product name. A property can similarly use NameBeginsWithS => Name.Length > 0 && Name[0] == 'S'. section 5.10.2
Lambdas also appear at application boundaries. In Program.cs, app.MapGet("endpoint/function", async context => { ... }); supplies an endpoint function. In a Blazor component, @onclick="@(e => IncrementCounter(e, 0))" passes a counter index to a shared event handler. A lambda in a Razor event attribute belongs inside a Razor expression; a plain handler name does not take parentheses. section 14.1.2 section 33.4.1
Buttons generated in a loop
When an @for loop generates counter buttons, assign int local = i inside the loop and use @onclick="@(() => IncrementCounter(local))". Each button then passes its local index to the handler. A reset button can instead call Counters.Remove(local) directly in its lambda. section 33.4.1
A lambda can also process a completed task through ContinueWith, although that continuation and its return types are easy to find confusing; async and await provide a simpler way to write asynchronous methods. section 5.13.1

















