C# Using Lamda Expressions

\lambda (lambda) the 11th letter of the Greek alphabet, has a common place in the mathematics world.

In the C# a lambda expression is an anonymous function that can contain expressions and statements.

Perhaps the most common use of lambdas is with enumerables. We also pass lambda expressions as arguments, for sorting or for searching in queries.

Anatomy of a lambda expression


To the left, we have arguments. The “x” is just a name—we can use any valid name. The result is on the right.

Below we use FindIndex, which receives a Predicate method. We specify this as a lambda expression.


Anonymous functions
When using lambdas as anonymous functions the => operator separates the parameters to a method from its statements in the method’s body.

It is easy to confuse the => as a comparator operator but in the case of lambdas it is easier to think of the => as “goes to”.

Output
2
2
2
2
4

Overview
Lambdas are made up of 3 parts:
Left side – This is the parameters. It can be empty. Sometimes it can be implicit (derived from the right).
Operator – operator => separates arguments from methods. It does not compare numbers
Right side – This is a statement list inside curly brackets with a return statement or an expression.