views:

338

answers:

5

This question was asked at interview.I need to have running total (only using Aggregate() )

from array

(i.e)

int[] array={10,20,30};

Expected output

10
30
60

when i use Aggregate (I applied some worst logic)

array.Aggregate((a, b) => { Console.WriteLine(a + b); return (a + b); });

1) It prints 30,60 ,for me there is no use of return (a+b).

2) In order to print 10 , i have to modify the array by adding element zero (i.e) {0,10,20,30}.

Is there any neat work could turn it out?

+5  A: 

try array.Aggregate(0, (a, b) => { Console.WriteLine(a + b); return (a + b); }); instead :-)

klausbyskov
+2  A: 

Aggregate has other overloads that work slightly differently -- take a look at this one: http://msdn.microsoft.com/en-us/library/bb549218.aspx:

public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source,
    TAccumulate seed,
    Func<TAccumulate, TSource, TAccumulate> func )
Tim Robinson
+1  A: 

You should specify the seed-value as 0:

int[] array = { 10, 20, 30 };
array.Aggregate(0, (a, b) => { Console.WriteLine(a + b); return a + b; });

This will output what you expect.

Johan Kullbom
+1  A: 
array.Aggregate(0, (a, b) => 
{ 
    Console.WriteLine(a + b); 
    return a + b;
});
Darin Dimitrov
+1  A: 
array.Aggregate(0, (progress, next) => { Console.WriteLine(progress + next); return (progress + next); });

Use the version of Aggregate that starts aggregating with a seed value, rather than that starts aggregating with the first pair.

DrPizza