Lambda Expressions are getting good recognition among developers and it would be
nice to have the next level of information regarding it.
Summary
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
var
result = list.Where(i => i == 100);
Example of Two Parameter Lambda
var
result = list.Where((i, ix) => i == ix);
Code Explained
In the above case the Where() method is having two overloads and we were using
the second overloaded method which takes Func<T, T, bool> as argument.
The first argument is the element itself and second would be the index. The
value of index will be passed by the caller.
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.
Scenario 1
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?
Setup Code
The following code can be used for creating the main list.
IList<int>
list = new List<int>();
list.Add(0);
// Value = Index
list.Add(2);
list.Add(2); // Value = Index
list.Add(1);
list.Add(4); // Value = Index
One Line Lambda Solution
var
sublist = list.Where((i, ix) => i == ix);
The Lengthy Solution
var
newList = new List<int>();
int
jx = 0;
foreach
(int j in list)
if (jx++ == j) //
Check index and increment index
newList.Add(j);
From the above code we can see without lambda expressions the solution will be
taking more than 1 lines.
Result
We can see the associated result of the console application. The source code is
attached with the article.
Summary
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.