.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expressions with Multiple Parameters

Posted By:Jean Paul       Posted Date: May 01, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

Lambda Expressions are 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 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 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); // Value = Index


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



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.

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend