In this article, I will explain the ways to calculate the sum of an Array of numbers using the C#. In general, there are lots of ways to find the sum of an array of numbers. There are mainly four ways to do this.
Let’s go through them one by one way.
Using Enumerable.Sum()
The Enumberable.Sum() is a method from System.Linq namespace. It returns the sum of numeric values. Check the below example.
using System; using System.Linq; public class ArraySum { public static void Main() { int[] arr = { 10, 20, 30, 40 }; int sum = arr.Sum(); Console.WriteLine(sum); Console.ReadLine(); } }
Using Enumerable.Aggregate()
The Enumerable.Aggregate() method performs an operation on each element of the list. In this method, operations are performed on the 1st and 2nd element of the list, and the result is carried forward, Then operation will be performed on the carried result and 3rd element.
using System; using System.Linq; public class SumArray { public static void Main() { int arr[] = { 10, 20, 30, 50 }; int sum = arr.Aggregate((result, next) => result + next); Console.WriteLine(sum); Console.ReadLine(); } }
Using Array.ForEach()
This method loops over each element of the Array. Check the below code.
Using System; public class SumArray { public static void Main() { int[] arr = { 10, 10, 30 }; int sum = 0; Array.ForEach(arr, i => sum = sum + i); Console.WriteLine(sum); Console.ReadLine(); } }
Using for loop
For loop is a very common and well-known method to calculate the sum of array elements.
using System; public class SumArray() { public static void Main() { int[] arr = { 10, 20, 310, 60 }; int sum = 0; for (int i = 0; i < arr.Length; i++) { sum = sum + arr[i]; } Console.WriteLine(sum); } }