What is Lambda Expression ?
Lambda expression is an inline delegate introduced with C # 3.0 language. It is an easy way to represent an anonymous method. Lambda is used to write anonymous functions which does not take parameter and which does not return anything. Lambda expression allows us to pass functions as arguments to a method call.
The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
It helps in avoiding to write a function specifically even when it is going to be used only once, as it allows writing the function inline where it is being used. It reduces typing speed as there is no need to specify the name of the function, its return type, and its access modifier.
How do we define a lambda expression?
Basic definition of Lambda is like: Parameters => Executed code.
Simple example is as follows:
x => x % 2 == 1
where n is the input parameter and n % 2 == 1 is the expression.
0 Comment(s)