Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum range of int's in List<int>

Tags:

c#

list

sum

I reckon this will be quite trivial but I can't work out how to do it. I have a List<int> and I want to sum a range of the numbers.

Say my list is:

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

How would I get the sum of the first 3 objects? The result being 6. I tried using Enumerable.Range but couldn't get it to work, not sure if that's the best way of going about it.

Without doing:

int sum = list[0] + list[1] + list[2]; 
like image 679
Bali C Avatar asked Apr 23 '12 16:04

Bali C


People also ask

How do you add numbers in a list in Python?

Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.


2 Answers

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.

like image 140
James Hill Avatar answered Oct 05 '22 17:10

James Hill


Or just use Linq

int result = list.Sum(); 

To sum first three elements:

int result = list.GetRange(0,3).Sum(); 
like image 36
David Young Avatar answered Oct 05 '22 18:10

David Young