C# - Running Total using Aggregate()
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 pr开发者_如何学编程int 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?
try array.Aggregate(0, (a, b) => { Console.WriteLine(a + b); return (a + b); });
instead :-)
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 )
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.
array.Aggregate(0, (a, b) =>
{
Console.WriteLine(a + b);
return a + b;
});
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.
精彩评论