国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

IEnumerable接口的Aggregate方法

2019-11-17 03:16:46
字體:
供稿:網(wǎng)友

IEnumerable接口的Aggregate方法

以前小豬為了累加一個集合中的類容通常會寫出類似這樣的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 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 隆回县| 蒲江县| 遂昌县| 巧家县| 普兰县| 克什克腾旗| 卢龙县| 湖口县| 柳江县| 台南市| 康平县| 屏东县| 乐亭县| 乳山市| 玉环县| 怀来县| 浦北县| 岱山县| 赤壁市| 江陵县| 冀州市| 台中市| 伊宁县| 左云县| 涞源县| 嘉荫县| 政和县| 遂宁市| 长子县| 凤庆县| 松溪县| 泽库县| 邻水| 吉首市| 徐汇区| 琼结县| 河曲县| 高邑县| 溧阳市| 通州区| 普洱|