• Aggregate累加器


    今天看东西的时候看见这么个扩展方法Aggregate(累加器)很是陌生,于是乎查了查,随手记录一下。
    直接看一个最简答的版本,其他版本基本没什么区别,需要的时候可看一下

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

    这个方法的功能其实是对,可枚举的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 ,如此依次的遍历执行下去,直至结束。

      再给一个例子可以看出许多应用。计算数据中的整数的个数

    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了。

  • 相关阅读:
    4.回归类算法目标值连续型
    springcloud笔记
    5.聚类算法kmeans
    FastdFS文件系统
    ElasticSearch
    cors解决跨域
    Swagger
    miaosha2:高并发抢购方案
    关于javascript中的constructor与prototype
    eclipse布署项目到weblogic时启动两次的问题
  • 原文地址:https://www.cnblogs.com/superCow/p/3804134.html
Copyright © 2020-2023  润新知