System.Linq.Enumerable 中的方法 Aggregate 函数

 
语法:
public static TSource Aggregate<TSource>(
	this IEnumerable<TSource> source,
	Func<TSource, TSource, TSource> func
)
类型参数
TSource

source 中的元素的类型。

参数
source
类型: System.Collections.Generic.IEnumerable < TSource >
要聚合的 IEnumerable<T>
func
类型: System.Func < TSourceTSourceTSource >
要对每个元素调用的累加器函数。
返回值
类型: TSource
累加器的最终值。
 
实例:

private void _do(object param)
{
string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words.
string[] words = sentence.Split(' ');

string reversed = words.Aggregate(this.funagg);

}

 

/// <summary>
/// Aggregate 中的应用函数
/// </summary>
/// <param name="returns">每次调用这个函数后的返回值,在再次调这个函数时传人</param>
/// <param name="b">集合中的元素</param>
/// <returns></returns>
string funagg(string returns, string b) {
return string.Format("'{1}','{0}'", returns, b);
}

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

类型参数
TSource
        source 中的元素的类型。

TAccumulate
        累加器值的类型。

TResult
       结果值的类型。

参数
source
      类型:System.Collections.Generic.IEnumerable<TSource>
     要聚合的 IEnumerable<T>。
seed
     类型:TAccumulate
     累加器的初始值。
func
    类型:System.Func<TAccumulate, TSource, TAccumulate>
    要对每个元素调用的累加器函数。
resultSelector
    类型:System.Func<TAccumulate, TResult>
    将累加器的最终值转换为结果值的函数。
返回值
   类型:TResult
   已转换的累加器最终值。

 

举例:

private void _do(object param)
{
  string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
  string longst = fruits.Aggregate("bana", fun1, fun2);
}

/// <summary>
/// 返回两个参数中字符较多那个
/// </summary>
/// <param name="returns">在Aggregate函数循环调用过程中,returns是上一次调用这个函数返回的值,next是集合中的元素 </param>
/// <param name="next"></param>
/// <returns></returns>
string fun1(string returns, string next) {
  return next.Length > returns.Length ? next : returns;
}

/// <summary>
/// 遍历集合(调用函数fun1)结束后,调用这个函数处理fun1返回值
/// </summary>
/// <param name="returns"></param>
/// <returns></returns>
string fun2(string returns) {
  return returns.ToUpper();
}

转载于:https://www.cnblogs.com/jyluzy/p/2013-9-27_1.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值