码迷,mamicode.com
首页 > 其他好文 > 详细

04 LINQ中的聚合函数(Aggregate function in LINQ)

时间:2016-01-16 21:09:44      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

试想一下,我们有一个List<int>数组,现在我们想对List中的所有值求和。在没学习LINQ之前我们会轻松的写出下面的代码:

static void Main(string[] args)
{
    List<int> array = new List<int>() { 1, 3, 3, 2, 7, 3, 2, 8, 5, 4, 6 };
    int sum = 0;
    foreach (int item in array)
    {
        sum += item;
    }
    Console.WriteLine(sum);
}

输出结果是:44

但是LINQ中为我们提供了一个扩展函数Aggregate,该函数有三个重载,其中最简单的重载是向该函数传入一个类型为Func<TSource, TSource, TSource>的代理。下面代码演示了如何使用该扩展函数:

List<int> array = new List<int>() { 1, 3, 3, 2, 7, 3, 2, 8, 5, 4, 6 };
int sum = 0;
sum = array.Aggregate((a, b) => a + b);
Console.WriteLine(sum);

同样,输出结果是:44

04 LINQ中的聚合函数(Aggregate function in LINQ)

标签:

原文地址:http://www.cnblogs.com/kuillldan/p/5136285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!