[Solved] sum up an array of integers in C# [closed]


It isn’t clear what you want… If you want to sum some numbers so that the sum stops summing when it reaches 1002 you can:

List<int> list = new List<int> { 4, 900, 500, 498, 4 };
var lst = list.Skip(2).Take(3);

int sum = 0;

foreach (int num in lst)
{
    int sum2 = sum + num;

    if (sum2 > 1002)
    {
        break;
    }

    sum = sum2;
}

Console.WriteLine(sum);

or you can

List<int> list = new List<int> { 4, 900, 500, 498, 4 };
var lst = list.Skip(2).Take(3);

int sum = 0;

foreach (int num in lst)
{
    sum += num;

    if (sum >= 1002)
    {
        break;
    }
}

Console.WriteLine(sum);

The first one will stop if by adding a number it would go over 1002, while the second will stop AFTER reaching 1002.

Note that both of these can’t be easily done directly in LINQ.

3

solved sum up an array of integers in C# [closed]