Sum range of int's in List<int>
Solution 1:
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.
Solution 2:
Or just use Linq
int result = list.Sum();
To sum first three elements:
int result = list.GetRange(0,3).Sum();