0

I'd like to optimise the following code into 1 line using LINQ Aggregate, however never used Aggregate function before and although I tried, I couldn't make it work..

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

instead of

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 ));

Any assistance please.. thanks in advance

1 Answers1

2

To tell the truth this is enough:

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

But, if you want Aggregate():

var sum = Groups.Select(x => x.Width).Aggregate((current, next) => current += next);
Farhad Jabiyev
  • 24,866
  • 7
  • 63
  • 96