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

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<int> list = new List<int>(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

Leave a Reply

Your email address will not be published. Required fields are marked *