0

I have just started C# but I can't figure out how you add all the values in a list.

For example, if you have:

List<int> values = new List<int> { 1, 2, 4, 8, 5, 10 };

How can I add every single value in this list, without manually putting it into a calculator?

Draken
  • 3,134
  • 13
  • 34
  • 54
  • 1
    Do you want to get total of all the numbers in the list? – Chetan Aug 13 '20 at 09:46
  • 1
    `int result = 0; foreach(int item in values) result += item;` if you don't want any Linq at the moment – Dmitry Bychenko Aug 13 '20 at 09:48
  • 3
    Does this answer your question? [How to sum up an array of integers in C#](https://stackoverflow.com/questions/2419343/how-to-sum-up-an-array-of-integers-in-c-sharp) – Draken Aug 13 '20 at 09:49

2 Answers2

6

Use Sum:

using System.Linq;

// ...

var total = values.Sum();

Don't forget to include using System.Linq at the top of the file.

Or, if you don't want to use LINQ, write a loop.

var total = 0;

foreach (var value in values)
{
    total += value;
}

// total equals 30
Rudey
  • 4,717
  • 4
  • 42
  • 84
1

Alternatively to linq, you must loop through the list and add it to a sum:

int sum = 0;
foreach(int nr in values)
{
  sum += nr;
}
Carra
  • 17,808
  • 7
  • 62
  • 75