木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2013-07-11 👁 5384 👍 0 💬 0 🔄 来源:本站原创
重载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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 简单三步手机连接360随身WiFi上网示例 下一篇 → 华易企鹅手机F1退出安全模式