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


Top 5 Contributors of the Month
david stephan

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

 Subscribe to Articles

One Line Lambda - To select last 3 items in the list and find sum

Posted By:Jean Paul       Posted Date: December 05, 2010    Points: 75    Category: LINQ    URL: http://www.dotnetspark.com  

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.
 

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable. 

IList list = new List(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count - 1; i >= list.Count - 3; i--)
      sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

  1. Little hectic code of for loop and decrementing index
  2. Reduced the number of lines from 3 to 1
  3. Helped in attaining the functionality in ease

 

 Subscribe to Articles

     

Further Readings:

Responses

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