C # improved Aggregate Extension

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.