Language: EN

csharp-funciones-lambda

What are and how to use lambda functions

A lambda function in C# is a concise syntax for defining 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. They are especially helpful in situations where you need to define a simple function that you will use only once (such as in filtering, mapping, or reducing collections).

Syntax of lambda functions

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

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

Basic Example

Let’s see it with an example. The following lambda function sums two numbers:

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

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

Here we have,

  • The lambda function takes two parameters x and y
  • 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 numeros = new List<int> { 1, 2, 3, 4, 5 };

var pares = numeros.Where(num => num % 2 == 0);

Transforming a collection,

var nombres = new List<string> { "Luis", "María", "Pedro" };

var mesanjes = nombres.Select(nombre => $"¡Hola, {nombre}!");

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 imprimirMensaje = mensaje => Console.WriteLine(mensaje);

imprimirMensaje("¡Hola desde una función lambda!");

Events

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

Button boton = new Button();

boton.Click += (sender, e) => Console.WriteLine("Botón clickeado");