Lambda Expressions with Multiple Parameters

Introduction

Lambda Expressions is getting good recognition among developers, and it would be nice to have the next level of information regarding it.

As you know, Lambda Expressions is an anonymous function that can contain expressions 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 Explanation

In the above case, the Where() method has two overloads, and we were using the second overloaded method, which takes Func<T, T, bool> as an argument.

Lamba1.gif

The first argument is the element itself, and the second is the index. The value of the 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.

You have got a list of random integers. We need to find the numbers whose value equals the index. How to achieve this in one line?

Code Setup for the main list

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 line.

Output

We can see the associated result of the console application. The source code is attached to the article.

Lamba2.gif

Summary

In this short article, we have seen the advantage of the Index parameter in Lambda expressions in reducing the code and increasing the speed of development as well as execution.


Recommended Free Ebook
Similar Articles