Language: EN

csharp-funciones-lambda

What are and how to use lambda functions

A lambda function is an anonymous function that can be defined inline without the need to formally name it.

These functions are useful for writing code in a more compact and readable way, especially in situations where you need to define simple functions at once, such as filtering, mapping, or reducing collections.

Lambda function syntax

The basic syntax of a lambda function in C# is as follows:

(parameters) => expression
  • Parameters: Are the input parameters of the lambda function, separated by commas if there is more than one.
  • Expression: Is the expression that is evaluated and returned as the result of the lambda function.

Basic Example

The following is a basic example of a lambda function that adds two numbers:

var sum = (x, y) => x + y;

Console.WriteLine(sum(5, 3)); // Output: 8

In this example, the lambda function takes two parameters x and y, and returns their sum as the result.

Practical Examples

In LINQ expressions

Lambda functions are commonly used in LINQ expressions to perform query operations on data collections.

For example, to filter a collection,

var numbers = new List<int> { 1, 2, 3, 4, 5 };

var evenNumbers = numbers.Where(num => num % 2 == 0);

Transform a collection,

var names = new List<string> { "John", "Mary", "Peter" };

var messages = names.Select(name => $"Hello, {name}!");

In general, for most expressions used in LINQ.

Delegates

Lambda functions can be assigned to delegate type variables to pass them as arguments to other functions or methods.

var printMessage = message => Console.WriteLine(message);

printMessage("Hello from a lambda function!");

Events

Lambda functions are useful for subscribing to events in a more concise and expressive way.

Button button = new Button();

button.Click += (sender, e) => Console.WriteLine("Button clicked");