tags:

views:

492

answers:

5

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[]?".

+8  A: 

Provided that you can use C# 3.5 and LINQ, try

int sum = arr.Sum(i => i);
Thomas Wanner
Thanks a lot - i assume you deserve the marker in this heartbeat finish. Especially for pointing out the C# 3.5 requirement.
Filburt
@Filburt / @Thomas: a minor correction: it's C# 3.0. The **.NET** version that provides the `Sum` extension method is version 3.5.
Ahmad Mageed
The identity lambda isn't necessary. Except to confuse the new guy on the team.
Will
+18  A: 

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);
Ahmad Mageed
+1 for the non-LINQ answer.
Michael Itzoe
Why such a convoluted pre 3.5 version? The `foreach` loop is available in all versions of C#.
Jørn Schou-Rode
@Jørn: the OP asked for a shorter approach. A `foreach` just substitutes one line of code for another and isn't shorter. Apart from that a `foreach` is perfectly fine and is more readable.
Ahmad Mageed
Point taken. Yet, the following saves 18 chars compared to your sample: `foreach (int i in arr) sum += i;`
Jørn Schou-Rode
+8  A: 

With LINQ:

arr.Sum()
Christopher
+3  A: 

It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.

unholysampler
+1 Very good point on performance improvement but honestly my initial wish was to get rid off the iteration.
Filburt
(nobody tell Fil that he just pushed the iteration a couple levels down the stack)
Will
@Will: Dude - don't expect me to believe if i don't write the code magic will happen ;-)
Filburt
I suspect it would have to be a VERY large array before such a parallel optimization would make sense.
Hightechrider
Yeah, since when did a for loop become bad practice?
Ed Swangren
@Fil the framework is made of rainbows and robot unicorns.
Will
A: 

Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.

Ben Voigt