简体   繁体   English

多维数组中的快速值总和(C#)

[英]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. 使用1D数组,我可以使用sum方法来获取所有值的总和。

int[] array = {6,3,1};
Console.WriteLine(array.Sum());

With a multidimensional array (3D in my case), this can't be done. 使用多维数组(在我的情况下为3D),这是不可能完成的。 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 . Sum完全是foreach There is no magic behind them. 他们背后没有魔力。 If you are so performance hungry use for instead of foreach . 如果你是这样的性能饿使用for代替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 你可以像这样在.net 4中并行化这个

var i = array.AsParallel().SelectMany(k => k).Sum();

Why should a foreach perform badly? 为什么foreach表现不好? 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 ). 所以也许有更美的方式,但不是更高效的方式(用大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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM