[筆記] C# LINQ Aggregate方法 初步了解

初步了解 C# LINQ Aggregate方法 

單純執行迴圈看結果
void Main()
{
    var numbers = new List<int> { 2, 4, 6, 8 };
    int test1 = numbers.Aggregate(func: (result, item) => {
      Console.Write($"result:{result} ");
      Console.WriteLine($"item:{item} ");
		
      return result;
    });
    Console.WriteLine($"test1:{test1} ");
}

輸出結果

加總測試: Sum
void Main()
{
    var numbers = new List<int> { 3, 5, 7, 9 };
    int test2 = numbers.Aggregate(func: (result, item) => {
	 
      Console.WriteLine($"result:{result} + item:{item} = {result + item}");
		
      return result + item;
    });
    //((3+5)+7)+9)
    Console.WriteLine($"test2:{test2} ");
}

輸出結果

取最小值測試: Min
void Main()
{
    var numbers = new List<int> { 5, 3, 7, 9 };
    int test3 = numbers.Aggregate(func: (result, item) => {
	 
      Console.WriteLine($"result: {result} item: {item} Return比較結果較小的值");
		
      if(result > item)
      {
        return item;
      }
	  
      return result;
	  
    });

    Console.WriteLine($"min: {test3} ");
}

 縮減程式

void Main()
{
    var numbers = new List<int> { 5, 3, 7, 9 };
    int test3 = numbers.Aggregate(func: (result, item) => {
	 
      Console.WriteLine($"result: {result} item: {item} Return比較結果較小的值");
		
      return result > item ? item : result;  
    });

    Console.WriteLine($"min: {test3} ");
}

輸出結果

取最大值測試: Max
void Main()
{
    var numbers = new List<int> { 5, 3, 7, 9 };
    int test4 = numbers.Aggregate(func: (result, item) => {
	 
      Console.WriteLine($"result: {result} item: {item} Return比較結果較大的值");
		
	  return result < item ? item : result;  
    });

    Console.WriteLine($"min: {test4} ");
}

 

取平均值測試: Average
void Main()
{
    var numbers = new List<int> { 5, 3, 7, 9 };
    int test5 = numbers.Aggregate(
	//設定起始值
    seed: 0 ,
    func: (result, item) => {
	  //先加總
        var sum = result + item;
	  
        Console.WriteLine($"result: {result} + item: {item} = {sum}");
        return sum;  
    },
    resultSelector: result => {
      //再除以分母
      return result / numbers.Count();
    });

    Console.WriteLine($"average: {test5} ");
}

輸出結果

Aggregate的多載方法

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.average?view=netframework-4.8

資料參考:

http://www.csharp-examples.net/linq-aggregate/

https://ithelp.ithome.com.tw/articles/10197334