我如何在这里使用LINQ Aggregate?

时间:2015-03-27 10:08:52

标签: c# linq

我想使用LINQ Aggregate将以下代码优化为1行,但之前从未使用过Aggregate函数,虽然我尝试过,但我无法使其工作..

var sum = Aggregate(0.0, (group) => group.width + ????);

而不是

double sum = 0.0;
double height = 1.0;
foreach (var group in Groups)
{
sum = sum + group.width;
}

var rectPosition = new Rectangular(anchor.x, anchor.y,new BoxDimension(sum, height ));

任何帮助请...提前感谢

1 个答案:

答案 0 :(得分:2)

说实话这已经足够了:

var sum = Groups.Select(x => x.Width).Sum();
var sum = Groups.Sum(x => x.Width);

但是,如果你想要Aggregate()

var sum = Groups.Select(x => x.Width).Aggregate((current, next) => current += next);