sum of a list c# code example
Example 1: add all elements in a list c#
using System.Collections.Generic;
using System.Linq;
List<int> intList = new List<int>(){1, 2, 3, 4};
int sum = intList.Aggregate((x, y) => x + y);
Example 2: c# sum of array elements#
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
int[] arr = { 3, 6, 4, 1, 6, 8 };
Array.IndexOf(arr, 6);
int maxValue = anArray.Max();
int maxIndex = anArray.ToList().IndexOf(maxValue);
Example 3: sum array c#
int[] array1 = { 1, 3, 5, 7 };
List<int> list1 = new List<int>() { 1, 3, 5, 7 };
int sum1 = array1.Sum();
int sum2 = list1.Sum();