Linq累加器函数Aggregate执行原理分析

重载1:public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)

示例
List<int> ids = new List<int>() { 1, 2, 3, 4 };
string str1 = string.Empty, str2 = string.Empty;
int result = ids.Aggregate((a, b) => { str1 += a + "\t"; str2 += b + "\t"; return a + b; });
Console.WriteLine("a:{0}\r\nb:{1}\r\nresult:{2}", str1, str2, result);

结果


分析
参数a保存func函数上次执行结果,a初始值为集合第一个元素,集合元素从第二个开始依次传给b到func函数进行运算,最后返回a的值。

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

示例
List<int> ids = new List<int>() { 1, 2, 3, 4 };
string str1 = string.Empty, str2 = string.Empty;
int result = ids.Aggregate(0, (a, b) => { str1 += a + "\t"; str2 += b + "\t"; return a + b; });
Console.WriteLine("a:{0}\r\nb:{1}\r\nresult:{2}", str1, str2, result);

结果


分析
参数a保存func函数上次执行结果,a初始值为种子值,集合元素从第一个开始依次传给b到func函数进行运算,最后返回a的值。

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

示例
List<int> ids = new List<int>() { 1, 2, 3, 4 };
string str1 = string.Empty, str2 = string.Empty, str3 = string.Empty;
int result = ids.Aggregate(0, (a, b) => { str1 += a + "\t"; str2 += b + "\t"; return a + b; }, c => { str3 += c + "\t"; return c + 5; });
Console.WriteLine("a:{0}\r\nb:{1}\r\nc:{2}\r\nresult:{3}", str1, str2, str3, result);

结果


分析
参数a保存func函数上次执行结果,a初始值为种子值,集合元素从第一个开始依次传给b到func函数进行运算,最后将a的值传给c到resultSelector进行运算并返回。

评论: 0 | 引用: 0 | 查看次数: 4945
发表评论
登录后再发表评论!