星期五, 5月 20, 2022

[LINQ] Aggregate

每次看 Aggregate 文件時都會感到眼花撩亂,不知道在寫甚麼,透過官方文件內容來練習並對應文字說明

Aggregate() 多載 1

Applies an accumulator function over a sequence.
public static TSource Aggregate<TSource> 
(
	this System.Collections.Generic.IEnumerable<TSource> source, 
	Func<TSource,TSource,TSource> func
);
string sentence = "the quick brown fox jumps over the lazy dog";
sentence.Split(' ').Aggregate(
	(workingSentence, next) => next + " " + workingSentence)
	.Dump("官方範例:反轉單字");
[LINQ] Aggregate-1

Aggregate() 多載 2

Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.
public static TAccumulate Aggregate<TSource,TAccumulate> 
(
	this System.Collections.Generic.IEnumerable<TSource> source, 
	TAccumulate seed, 
	Func<TAccumulate,TSource,TAccumulate> func
);
int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
ints.Aggregate(
	0,
	(total, next) => next % 2 == 0 ? total + 1 : total)
	.Dump("官方範例:計算偶數");
[LINQ] Aggregate-2

Aggregate() 多載 3

Applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.
public static TResult Aggregate<TSource,TAccumulate,TResult> 
(
	this System.Collections.Generic.IEnumerable<TSource> source, 
	TAccumulate seed, 
	Func<TAccumulate,TSource,TAccumulate> func, 
	Func<TAccumulate,TResult> resultSelector
);
string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
fruits.Aggregate(
	"banana",
	(longest, next) => next.Length > longest.Length ? next : longest,
	fruit => fruit.ToUpper())
	.Dump("官方範例:找出最常字串並轉為全大寫");
[LINQ] Aggregate-3

觀察練習

把上述 [官方範例:計算偶數] 範例拿來修改,觀察不同資料型態使用
string[] demo = { "4", "8", "8", "3", "9", "0", "7", "8", "2" }; // 故意弄成字串陣列
demo.Aggregate(
	Convert.ToInt64(0), // seed 會影響 total 資料型別
	(total, next) => Convert.ToInt64(next) % 2 == 0 ? total + 1 : total,
	finalResult => DateTime.Today.AddDays(finalResult)
	.Dump("觀察練習"));
[LINQ] Aggregate-5 

上述範例執行結果

[LINQ] Aggregate-4

沒有留言:

張貼留言