How to sum up an array of integers in C#
Is there a better shorter way than iterating over the array?
int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
clarification:
Better primary means cleaner code but hints on performance improvement are also welcome. (Like already mentioned: splitting large arrays).
It's not like I was looking for killer performance improvement - I just wondered if this very kind of syntactic sugar wasn't already available: "There's String.Join - what the heck about int[]?".
Provided that you can use .NET 3.5 (or newer) and LINQ, try
int sum = arr.Sum();
Yes there is. With .NET 3.5:
int sum = arr.Sum();
Console.WriteLine(sum);
If you're not using .NET 3.5 you could do this:
int sum = 0;
Array.ForEach(arr, delegate(int i) { sum += i; });
Console.WriteLine(sum);