As you know, Lambda Expressions is
an anonymous function that can contain expression or statements. The
lambda expression uses the => (goes to) operator.
Example of One Parameter Lambda
result = list.Where(i => i == 100);
Example of Two Parameter Lambda
result = list.Where((i, ix) => i == ix);
In the above case the Where()
method is having two overloads and we were using the second overloaded method
which takes Func as argument.
The first argument is the element itself and second would be the index. The value of index will be passed by the
Applications of Index Parameters
It could be of rare applications
where we needed the lambda index parameter.
I have seen in many interviews they ask scenarios based on it. Some
of the scenarios are given below.
You have got a list of random integers. We need to find the numbers whose value
equals to the index. How to achieve this
in one line?
The following code can be used for creating the main list.
list = new List<int>();
list.Add(0); // Value = Index
list.Add(2); // Value = Index
list.Add(4); // Value = Index
One Line Lambda
var sublist = list.Where((i, ix) => i == ix);
The Lengthy Solution
var newList = new List<int>();
int jx = 0;
j in list)
if (jx++ ==
j) // Check index and increment index
From the above code we can see without lambda expressions
the solution will be taking more than 1 lines.
We can see the associated result of the console
application. The source code is attached
with the article.
In this short article, we have seen the advantage of Index
parameter in Lambda expressions in reducing the code and increasing the speed
of development as well as execution.