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

时间:2023-03-09 16:55:19
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<TSource, TSource, TSource>
要对每个元素调用的累加器函数。

返回值

类型: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();
}