Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# About IEnumerable<T>.Aggregate

Tags:

I did some tests about IList<T>.Aggregate(), but the answer does not make sense to me.

List<int> Data1 = new List<int> { 1,0,0,0,0};

var result = Data1.Aggregate<int>((total, next) => total + total);

The result is 16.

I expected it to be 32.

Can someone explain?

like image 583
retide Avatar asked May 19 '11 20:05

retide


1 Answers

Aggregate doesn't run its callback for the first element in the list. Rather, the first element is used as the initial value for the accumulator (total).
Therefore, your callback only runs four times, not five, and 24 = 16.

like image 196
SLaks Avatar answered Sep 20 '22 06:09

SLaks