首页 > 学院 > 开发设计 > 正文

IEnumerable接口的Aggregate方法

2019-11-17 03:16:46
字体:
来源:转载
供稿:网友

IEnumerable接口的Aggregate方法

以前小猪为了累加一个集合中的类容通常会写出类似这样的C#代码:

string result ="":foreach (var item in items){     result+=item.centent;}

大概意思就是遍历集合中的每一项来累加其中的一个值。今天小猪才发现其实.NET的集合已经提供了该功能:那就是小猪现在讲的IEnumerable<T>接口的Aggregate方法:

该方法提供了两个重载版本

版本1:Aggregate<TSource>(Func<TSource, TSource, TSource>):已重载。 对序列应用累加器函数。 (由 Enumerable 定义。)

版本2:Aggregate<TSource, TAccumulate>(TAccumulate, Func<TAccumulate, TSource, TAccumulate>)已重载。 对序列应用累加器函数。 将指定的种子值用作累加器初始值。 (由Enumerable 定义。)

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

由定义可以看出该方法是个拓展方法,所以在使用时不需要传递第一个参数。

此方法的工作原理是对source中的每个元素调用一次func。每次调用func时,Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)都将传递序列中的元素和聚合值(作为func的第一个参数)。将seed参数的值用作聚合的初始值。用func的结果替换以前的聚合值。Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)返回func的最终结果。

若要简化一般的聚合运算,标准查询运算符还可以包含一个通用的计数方法(即Count)和四个数值聚合方法(即Min、Max、Sum和Average)。

下面的代码示例演示如何使用Aggregate应用累加器函数和使用种子值。

int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };// Count the even numbers in the array, using a seed value of 0.int numEven = ints.Aggregate(0, (total, next) =>next % 2 == 0 ? total + 1 : total);Console.WriteLine("The number of even integers is: {0}", numEven);// This code PRoduces the following output://// The number of even integers is: 6 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表