Aggregate累加器

今天看東西的時候看見這麼個擴展方法Aggregate(累加器)非常陌生,因而乎查了查,隨手記錄一下。
直接看一個最簡答的版本,其餘版本基本沒什麼區別,須要的時候可看一下ui

public static TSource Aggregate<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func
)this

這個方法的功能實際上是對,可枚舉的IEnumerable<TSource>某種數據,從前兩個遍歷對象開始逐個,做爲輸入進行自定
義的操做,這個方法仍是蠻有用的,看幾個例子。調試

private void button7_Click(object sender, EventArgs e)
        {
            string sentence = "the quick brown fox jumps over the lazy dog";
            string[] words = sentence.Split(' ');
            Func<string, string, string> temp = test;
            string reversed = words.Aggregate("",temp);
            //string reversed=words.Aggregate((workingSentence, next) =>next + " " + workingSentence);
            MessageBox.Show(reversed);
        }


        public string test(string para1, string para2)
        {
            return para2 + " " + para1;
        }

  這裏我沒用msdn直接提供的lambda方式,目的就是爲了方便調試查看下。先給出結果吧dog lazy the over jumps fox brown quick the對象

其執行過程是這樣滴,第一次 para1 爲the ,para2爲 quick,返回了 quick the, 而且做爲下次的 para1,para2 爲brown ,如此依次的遍歷執行下去,直至結束。blog

  再給一個例子能夠看出許多應用。計算數據中的整數的個數string

private void button8_Click(object sender, EventArgs e)
        {
            int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
            int numEven = ints.Aggregate(0, (total, next) =>next % 2 == 0 ? total + 1 : total);
            MessageBox.Show("The number of even integers is: " + numEven);
        }

  恩恩,這都是msdn直接給出的例子,那麼不少相似的統計或者計算累的需求是否是就能夠考慮下Aggregate了。it

相關文章
相關標籤/搜索