21

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?

Brian
  • 25,523
  • 18
  • 82
  • 173
retide
  • 1,170
  • 1
  • 13
  • 31
  • Um... why do you think it should be 30? – SLaks May 19 '11 at 20:15
  • var result = Data1.Aggregate(0, (total, next) => total + total); The answer is 0 this time, i guess it because initial value for the accumulator (total) is 0, and pass total = 0 in the callback func. – retide May 19 '11 at 20:48
  • You are correct. That will completely ignore the items in the list. – SLaks May 19 '11 at 20:52

1 Answers1

21

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964