Sum range of int's in List<int>

You can accomplish this by using Take & Sum:

var list = new List<int>()
{
    1, 2, 3, 4
};

// 1 + 2 + 3
int sum = list.Take(3).Sum(); // Result: 6

If you want to sum a range beginning elsewhere, you can use Skip:

var list = new List<int>()
{
    1, 2, 3, 4
};

// 3 + 4
int sum = list.Skip(2).Take(2).Sum(); // Result: 7

Or, reorder your list using OrderBy or OrderByDescending and then sum:

var list = new List<int>()
{
    1, 2, 3, 4
};

// 3 + 4
int sum = list.OrderByDescending(x => x).Take(2).Sum(); // Result: 7

As you can see, there are a number of ways to accomplish this task (or related tasks). See Take, Sum, Skip, OrderBy & OrderByDescending documentation for further information.

Tags:

C#

List

Sum