What is a lambda expression?
What is a lambda expression?
506
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023A lambda expression in C# is an anonymous function that can be used to encapsulate a small amount of code. Lambda expressions are often used in functional programming, but they can also be used in other programming paradigms.
A lambda expression is defined using the
lambdakeyword. The syntax for a lambda expression is as follows:Code snippet
The
parameterssection is optional and can be used to specify the parameters that the lambda expression takes. Theexpressionsection is the body of the lambda expression and contains the code that the lambda expression executes.Here is an example of a lambda expression that adds two numbers:
Code snippet
This lambda expression takes two integers as parameters and returns the sum of the two integers.
Lambda expressions can be used in a variety of situations, such as:
Code snippet
The
Where()method takes a lambda expression as a parameter. The lambda expression in this case checks if the number is greater than 10. If the number is greater than 10, the number is added to thefilteredNumberslist.Code snippet
The
Select()method takes a lambda expression as a parameter. The lambda expression in this case converts the number to a string. The strings are then added to thestringslist.Code snippet
The
addTwoNumbers()method takes two integers as parameters and returns the sum of the two integers. Thedelegatevariable is an anonymous delegate that refers to theaddTwoNumbers()method. Theresultvariable is the result of calling the anonymous delegate with the values 1 and 2.