以前小豬為了累加一個集合中的類容通常會寫出類似這樣的C#代碼:
string result ="":foreach (var item in items){ result+=item.centent;}大概意思就是遍歷集合中的每一項來累加其中的一個值。今天小豬才發(fā)現(xiàn)其實.NET的集合已經(jīng)提供了該功能:那就是小豬現(xiàn)在講的IEnumerable<T>接口的Aggregate方法:
該方法提供了兩個重載版本
版本1:Aggregate<TSource>(Func<TSource, TSource, TSource>):已重載。 對序列應(yīng)用累加器函數(shù)。 (由 Enumerable 定義。)
版本2:Aggregate<TSource, TAccumulate>(TAccumulate, Func<TAccumulate, TSource, TAccumulate>)已重載。 對序列應(yīng)用累加器函數(shù)。 將指定的種子值用作累加器初始值。 (由Enumerable 定義。)
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source,TAccumulate seed,Func<TAccumulate, TSource, TAccumulate> func)
由定義可以看出該方法是個拓展方法,所以在使用時不需要傳遞第一個參數(shù)。
此方法的工作原理是對source中的每個元素調(diào)用一次func。每次調(diào)用func時,Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)都將傳遞序列中的元素和聚合值(作為func的第一個參數(shù))。將seed參數(shù)的值用作聚合的初始值。用func的結(jié)果替換以前的聚合值。Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)返回func的最終結(jié)果。
若要簡化一般的聚合運算,標(biāo)準(zhǔn)查詢運算符還可以包含一個通用的計數(shù)方法(即Count)和四個數(shù)值聚合方法(即Min、Max、Sum和Average)。
下面的代碼示例演示如何使用Aggregate應(yīng)用累加器函數(shù)和使用種子值。
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 新聞熱點
疑難解答