A lambda expression within a query operator is evaluated on request and works on each component in the input sequence individually rather than the entire sequence. LINQ Lambda expressions allow developers to feed their logic into the basic LINQ query operators. The developer in the following example has used the 'Where' operator with a lambda expression to recover the odd values from a provided list.
Lambda Type Inference
Type inference is useful in various circumstances in C#, even when the types aren't explicitly specified. Nevertheless, type inference will only operate in the case of a lambda expression if each type has been provided, as the compiler must be satisfied.
Lambda Expressions with Variable Scope
Variables launched within a lambda expression are not intended to be visible in an outer procedure, according to several regulations when employing variable scope in a lambda expression. There's also a restriction that says a captured variable can't be garbage collected until the delegate that references it qualifies for garbage collection. Furthermore, it is against the rules to utilise a return statement within a lambda expression to induce a surrounding method to return.
Expression Tree
Lambda expressions are often utilised in the development of Expression Trees. An expression tree is a data structure that resembles a tree in which each node represents an expression, such as a method call or a binary operation, such as x<y.
Lambda Statement
Statement lambdas, which comprises 2 or 3 statements, are also available, but they are not employed in creating expression trees. In a lambda statement, a return statement must be written.
Lambdas are used as arguments in LINQ queries dependent on methods, and they are never allowed to appear on the left side of operators like or as, as opaque methods are.
Although LINQ Lambda expressions are similar to anonymous methods, they are not limited to merely being used as delegates.
Some things to keep in mind while utilising LINQ lambda expressions:
- The closure is a characteristic of LINQ lambda expressions that allows you to access variables within the lambda expression block. To avoid any problems, closing should be used with caution.
- A LINQ lambda expression can have arguments and return a value.
- Inside a LINQ lambda expression, it is impossible to run any unsafe code.
- So no need for angle brackets in a lambda expression if there is only one statement, but curly brackets and the return value are required for several statements.
- With a lambda expression, parameters can be described in a variety of ways.
- On the left side of the operator, lambda expressions are not to be used.