![]() |
VOOZH | about |
Lambda expressions in C# provide a concise way to represent anonymous methods. They are essentially a shorthand syntax for creating delegates and are commonly used to pass behavior as parameters. The lambda operator (=>) separates input parameters (left side) from the expression or statements (right side).
Represents a single expression that returns a value.
Syntax:
input => expression;
Represents a block of statements enclosed in braces.
Syntax:
input => { statements };
In the below example, a list of integers is processed using lambda expressions to calculate the square of each element and filter numbers divisible by 3.
The list: 36 71 12 15 29 18 27 17 9 34 Squares: 1296 5041 144 225 841 324 729 289 81 1156 Numbers Divisible by 3: 36 12 15 18 27 9
Lambda expressions can also be used with custom objects. The following example sorts a list of students by name using a lambda expression.
1 Liza 4 Stefani 2 Stewart 3 Tina 5 Trish
Note: Sorting rearranges the order of objects in the list based on the specified condition (Name). The RollNo values remain unchanged and stay associated with their respective student objects.