Fast sum of values in a multidimensional array (C#)
With a 1D array, I can use the sum method to get the sum of all the values.
int[] array = {6,3,1};
Console.WriteLine(array.Sum());
With a multidimensional ar开发者_JAVA百科ray (3D in my case), this can't be done. Obviously I could go all foreach on it, but this seems verbose and I suspect it will perform badly.
Is there a way to flatten the array? Or a nice way just to get the sum that I've not seen?
Sum does exactly foreach
. There is no magic behind them. If you are so performance hungry use for
instead of foreach
. You can do this in parallel also, this operation can be easily parallelized.
this'll do the trick.
var i = array.SelectMany(j => j).Sum()
you could parallelize this in .net 4 like this
var i = array.AsParallel().SelectMany(k => k).Sum();
Why should a foreach
perform badly? You have to read every value at least once to calculate the sum. There is no way around this (assuming "random" values, of course). So maybe there is a more beautyful way, but not a more performant one (speaking in terms of Big O).
If you have a jagged array and would like clean code you could use
int[][] array = { new []{ 6, 3, 1 }, new []{ 6, 3, 1 } };
Console.WriteLine(array.Sum(i => i.Sum()));
精彩评论