Lambda expressions in C# are a concise and powerful way to write inline functions that can be used as delegates or functional interfaces. Lambda expressions allow you to write code that is more readable and maintainable by reducing the amount of boilerplate code required for creating delegates or functional interfaces.
A lambda expression is an anonymous function that can be assigned to a delegate or functional interface. It consists of a parameter list, an arrow operator, and a body. The parameter list specifies the input parameters to the lambda expression, and the body specifies the code to be executed when the lambda expression is called.
Here’s a simple example of a lambda expression that takes an integer as input and returns its square:
int square = ((int x) => x * x)(5);
In this example, the lambda expression takes an integer `x` as input, multiplies it by itself, and returns the result. The lambda expression is then called with an input value of `5`, and the result is assigned to the variable `square`.
Lambda expressions can also be used with LINQ queries to filter, transform, or aggregate data. Here’s an example of a LINQ query that uses a lambda expression to filter a list of strings that start with the letter “A”:
Listlist = new List { "Apple", "Banana", "Apricot" }; var result = list.Where(s => s.StartsWith("A"));
In this example, the lambda expression `s=> s.StartsWith(“A”)` is used to define a filter condition for the `Where` method. The lambda expression takes a string `s` as input and returns `true` if the string starts with the letter “A”. The `Where` method then uses this lambda expression to filter the list and returns a new list that contains only the strings that start with “A”.
Lambda expressions can also be used with other functional interfaces, such as `Func`, `Action`, and `Predicate`. These interfaces define common delegate types that can be used to pass functions as arguments to other methods.
Here’s an example of a lambda expression that is used with the `Func` delegate to calculate the sum of two integers:
Funcsum = (x, y) => x + y; int result = sum(2, 3); // result is 5
In this example, the lambda expression `(x, y) => x + y` takes two integers `x` and `y` as input and returns their sum. The `Func` delegate is then used to assign this lambda expression to a variable called `sum`, which can be used to calculate the sum of two integers by calling the delegate with two integer arguments.
Overall, lambda expressions are a powerful and flexible feature in C# that can be used to write concise and readable code. By using lambda expressions, you can write code that is more expressive, composable, and reusable.