我正在尝试学习C#,并使用Aggregate。我可以使用减少Javascript中的问题,但由于某种原因我无法让我的代码运行。
我的最终目标是获取一个字符列表(这些都是数字),将它们转换为数字,聚合它们,然后返回一个值。但就目前而言,我只想让Aggregate工作。
我在进行任何聚合之前设置了这个:int[] test = {1,2,3,4,5};
当我有这段代码时:
int result = test.Aggregate ((current, total) => {
current += 1;
current + total;
});
我被告知:“只有赋值,调用,递增,递减和新对象表达式才能用作语句” 但是我见过多行lambda函数的例子。
我可以移除current += 1;
行和花括号,它会起作用,但我的目标是在每次聚合之前运行几件事。
如何让lambda表达式执行多行代码?
答案 0 :(得分:3)
current + total
在该上下文中无效。它仅对单行lambda的简写形式有效,没有花括号。否则,您需要一个明确的return
语句。
您需要将其改写为return current + total;
如果在没有大括号的情况下使用它,则return
是隐含的。
答案 1 :(得分:2)
返回值并使用花括号的Lambda需要一个'return'语句:
int[] test = { 1, 2, 3, 4, 5 };
int result = test.Aggregate((current, total) =>
{
current += 1;
current += total;
return current;
});