我正在尝试从另一个数组创建一个数组,但不是在我对第一个数组中的每个项目进行一些计算之前。
如您所见,我尝试使用函数 Aggregate fromSystem.Linq在结果数组的每个项目中获取,第一个数组项目的结果 + 先前值的总和(即int[] value = {a, b, c, d)- int[] result = {a, a+b, a+b+c, a+b+c+d}。但是,我使用它的方式没有t 给我预期的结果。
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}
在这个程序中,我只是尝试将先前值的总和添加到每个结果项的当前值,因为这是我目前需要的。但是,如果有人有一个解决方案允许我在将其存储到新数组中之前进行任何类型的计算,那就太好了。