tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Aggregating with increments

5 Oct 2010 1 mins .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;
		}
		else
		{
			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. 😃

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.