tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Aggregating with increments

5 Oct 2010 .NET, C#, LINQ

Similarly to previous method for Interleaving two IEnumerables I needed one method for doing kind of aggregate, but also to know about the intermediate steps. I could abuse the Aggregate method either directly or indirectly but I’m always more happy with clean solution.

The method is pretty simple (but before I did some rework, it was ugly 😉). It takes, apart from the IEnumerable, two functions. One for setting up the initial value for the first item and one for getting result for next step.

internal static IEnumerable<TResult> IncrementalAggregate<TSource, TResult>(this IEnumerable<TSource> data,
	Func<TSource, TResult> init,
	Func<TSource, TResult, TResult> nextResult)
	bool first = true;
	TResult intermediate = default(TResult);
	foreach (var item in data)
		if (first)
			intermediate = init(item);
			first = false;
			intermediate = nextResult(item, intermediate);
		yield return intermediate;

With it you can do i.e. summing the numbers and know what the intermediate sums were. Yes, sounds weird, but you might need it, one day as I did. 😃