-1

How do I shorten my code to find the sum of numbers in an array.

var numbers= new double[4]; 
numbers[0]=12.7;
numbers[1]=10.4;
numbers[2]=9.2;
numbers[3]=8.5;
var results=numbers[0]+numbers[1]+numbers[2]+numbers[3];
Console.WriteLine(results);

My goal is to shorten this code to something like results = sum(numbers[0:5]) like in python.

Please, what is he c# equivalent of this ?

Julian
  • 33,915
  • 22
  • 119
  • 174

2 Answers2

3

Use could use .Sum (from System.Linq)

e.g to sum all:

var results = numbers.Sum(n => n);

If you need only of the first results, e.g. the sum of the first 3, you could do:

var resultsFirst3 = numbers.Take(3).Sum(n => n);
Julian
  • 33,915
  • 22
  • 119
  • 174
0

Although Julian's answer is the best approach, you could also do it without the use of LINQ (not saying that you should). A more classic approach would be something like this:

var numbers= new double[4]; 
numbers[0]=12.7;
numbers[1]=10.4;
numbers[2]=9.2;

double sum = 0;

foreach (var num in numbers)
{
    sum += num;
}

Console.WriteLine("The sum is: " + sum);

As you can see, this is quite a bit longer, less elegant and (if you ask me) harder to read. So I would deffinitely go for the LINQ approach.

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96