我正在尝试从另一个数组创建一个数组,但在我对第一个数组进行每个项目进行一些计算之前。
如您所见,我尝试使用System.Linq
的函数汇总以在结果数组的每个项目中获取,这是第一个数组的结果 先前值的总和(即int[] value = {a, b, c, d)
-int[] result = {a, a+b, a+b+c, a+b+c+d}
。我用它没有给我预期的结果。
using System;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// First array
int[] value = { 1, 2, 3, 4, 5 };
// Result array with same Length of first one
int[] result = new int[value.Length];
for (int i = 0; i < value.Length; i++)
{
result[i] = value.Aggregate((sum, next) => sum + next);
Console.WriteLine(result[i]);
}
}
}
}
// Output
{15, 15, 15, 15, 15}
// Expected output
1, 1+2=3, 3+3=6, 6+4=10, 10+5=15
{1, 3, 6, 10, 15}
在此程序中,我只是尝试将上一个值的总和添加到结果的当前值中,因为这是我目前需要的。但是,如果某人有一个解决方案,可以在将其存储在新数组中之前进行任何类型的计算。
此代码仅通过一次数组,复杂性为o(n(。
var sum = 0;
var results = values.Select(item => sum += item).ToArray();
这是因为您每次都在评估整个数组,因此每次总和最终。将呼叫添加到接收函数中,以便您仅将项目添加到当前项目中。
for (int i = 0; i < value.Length; i++)
{
result[i] = value.Take(i + 1).Aggregate((sum, next) => sum + next);
Console.WriteLine(result[i]);
}