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 

 

转载于:https://www.cnblogs.com/smallerpig/p/3646229.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值