LINQ Aggregate operator to perform an accumulator operation on items of a sequence

By Indranil Chatterjee

This article illustrates how to use the Aggregate<T> operator from LINQ to perform an accumulator operation on all items of a sequence.

The Aggregate<TSource> operator from LINQ allows to run an accumulator function over the items of a sequence. There are different overloads. In its simplest form, it takes an instance of Func<TSource, TSource, TSource>. TSource is the type of source element. This uses the first element of the sequence as its seed. The first & second arguments of the Func delegate represent the current aggregated value and the current sequence item respectively. The Func returns and replaces the current aggregated value. Aggregate returns the final aggregated value.

Here is an example to find the string of maximum length from a given set:

string[] strings = { "Small", "It is fairly big", "Not so small" };
var longestString = strings.Aggregate(
(longest, next) => next.Length > longest.Length ? next : longest);

Console
.WriteLine("Longest string: {0}", longestString);

The overload Aggregate<TSource, TAccumulate> allows the accumulator type to be different from sequence element type & Aggregate<TSource, TAccumulate, TResult> takes an extra Func<TAccumulate, TResult> parameter which allows us to specify a selector operation on the final accumulated value.

LINQ Aggregate operator to perform an accumulator operation on items of a sequence  (687 Views)