This post will discuss how to sum up an array of integers in C#.

1. Using Enumerable.Sum Method

Starting with .NET 3.5, you can use the Enumerable.Sum method to compute the sum of a sequence of numeric values. It is available in System.Linq namespace and can be used as follows:

Download  Run Code

Output:

Sum is 16

 
The sum() method is overloaded for Decimal, Double, Int32, and Int64 values. For other numeric data types like Short and Long, do as follows:

Download  Run Code

Output:

Sum is 16

2. Using Enumerable.Aggregate Method

Another efficient way of accomplishing this would be with the Aggregate() method by LINQ, which applies an accumulator function over a sequence. Here’s an example of its usage:

Download  Run Code

Output:

Sum is 16

3. Using ForEach method

If you don’t prefer LINQ or do not use .NET 3.5 or above, you can use a foreach loop to compute the sum of an array of integers.

Download  Run Code

Output:

Sum is 16

 
Here’s an equivalent version using the Array.ForEach method.

Download  Run Code

Output:

Sum is 16

That’s all about summing up an array of integers in C#.