The Enumerable. Aggregate extension method is the first method (in alphabetical order) of the Enumerable class in the System. Linq namespace, but it is indeed a relatively complex method in Enumerable.
MSDN describes it as follows:Apply the accumulator function to the sequence.There are also some instructions in the remarks. The general idea is that this method is complicated. Generally, Sum, Max, Min, and Average can be used.
Look at the following code. With Sum, who else will use Aggregate!
It's also easy. It's just a loop! In the preceding lambda expressions, parameters a and n correspond to current and enumerator. Current, which are quite understandable.
Now we wantSum of the numbers with an even position in an integer Array), Where can be used with Sum:
Public static void Test5 ()
{
Int [] nums = new int [] {10, 20, 30, 40, 50 };
Int sum1 = nums. Where (n, I) => I % 2 = 0). Sum (); // 10 + 30 + 50
}
This Where extension is well designed. It not only brings out the value "n" of a certain item, but also brings out the position "I" of the item ".
Aggregate does not work! Let's improve it:
// Improved Aggerate extension (sample code, please add a Null Value Check for actual use)
Public static TSource Aggregate <TSource> (this IEnumerable <TSource> source, Func <TSource, TSource, int, TSource> func)
{
Int index = 0;
Using (IEnumerator <TSource> enumerator = source. GetEnumerator ())
{
Enumerator. MoveNext ();
Index ++;
TSource current = enumerator. Current;
While (enumerator. MoveNext ())
Current = func (current, enumerator. Current, index ++ );
Return current;
}
}
The improved Aggregate is more powerful, and the algorithm for the number of locations and locations in the previous step can be written as follows:
Public static void Test6 ()
{
Int [] nums = new int [] & nbs