如何计算结果超过Int32.Max值的int数组的总和

Leg*_*nds 4 c#

例如,我们有一个int数组:

var array = new int[]{ 2147483647, 2147483647, 2147483647, 2147483647};
Run Code Online (Sandbox Code Playgroud)

计算数组条目总和的最简单方法是什么,但就上面提供的示例而言

array.Sum()

结果是:

算术运算导致溢出

因为结果不再是int ..

Ste*_*eve 13

因为数组中的值的总和溢出,所以Int32.MaxValue您被迫将元素转换为long

var array = new int[]{ 2147483647, 2147483647, 2147483647, 2147483647};
var total = array.Sum(x => (long)x);
Console.WriteLine(total);
Run Code Online (Sandbox Code Playgroud)

您可以看到total变量的类型为Int64

Console.WriteLine(total.GetType());
Run Code Online (Sandbox Code Playgroud)

  • 有人贬低了,我想知道答案中是否有问题,谢谢 (2认同)

Mat*_*and 7

史蒂夫的回答非常适合你的问题.但是,如果需要存储长度超过可以使用的典型数据类型的值的总和BigInteger.

var array = new [] { long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue };
var result = new BigInteger();
result = array.Aggregate(result, (current, i) => current + i);
Run Code Online (Sandbox Code Playgroud)

此解决方案也适用于您提供的阵列.