LINQ中Aggregate的用法

本文導讀:LINQ中的Aggregate可用於集合的簡單的累加、階乘和一些更加複雜的運算,Aggregate配合lambda讓原來需要很多行代碼才能實現的功只要很少的代碼就搞定。下面介紹LINQ中Aggregate的簡單用法

LINQ中的Aggregate可以做一些複雜的聚合運算,例如累計求和,累計求乘積。

Aggregate接受2個參數,一般第一個參數是稱爲累積數(默認情況下等於第一個值),而第二個代表了下一個值。第一次計算之後,計算的結果會替換掉第一個參數,繼續參與下一次計算。

 

一、Aggregate的源碼分析

Aggregate在內部其實也僅僅是“普通做法”一模一樣的源代碼,Aggregate做的是一層代碼封裝

 

 

二、LINQ中的Aggregate實例

 

1、使用Aggregate語法做階乘運算

 

 
C# 代碼   複製

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
            var numbers = GetArray(5);
            var result = (from n in numbers
                         select n).Aggregate(
                            (total, next) =>
{
return total * next;
                            });
            Console.WriteLine("5的階乘爲:{0}",result);//返回120,也就是1*2*3*4*5

        }
static IEnumerable<int> GetArray(int max) {
            List<int> result = new List<int>(max);
for (int i = 0; i < max; i++)
{
                result.Add(i+1);
            }
return result;
        }
    }
}

 

2、Aggregate用於集合的簡單的累加、階乘

 

 
C# 代碼   複製

using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5 };
int result = array.Aggregate((a, b) => b + a);
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15
 Console.WriteLine(result);
 result = array.Aggregate((a, b) => b * a);
// 1 * 2 = 2
// 2 * 3 = 6
// 6 * 4 = 24
// 24 * 5 = 120
 Console.WriteLine(result);
 }
}
//輸出結果: 
//15 
//120 

 

3、Aggregate,在字符串中反轉單詞的排序

 

 
C# 代碼   複製

string sentence = "the quick brown fox jumps over the lazy dog";
string[] words = sentence.Split(' ');
string reversed = words.Aggregate((workingSentence, next) =>next + " " + workingSentence);
Console.WriteLine(reversed);
//輸出結果: 
//dog lazy the over jumps fox brown quick the 

 

4、使用 Aggregate 應用累加器函數和結果選擇器

下例使用linq的Aggregate方法找出數組中大於"banana", 長度最長的字符串,並把它轉換大寫。

 

 
C# 代碼   複製

string[] fruits ={ 
"apple", "mango", "orange", "passionfruit", "grape" 
};
string longestName = 
  fruits.Aggregate("banana",
     (longest, next) =>
      next.Length > longest.Length ? next : longest,
     fruit => fruit.ToUpper()); 
 Console.WriteLine(
"The fruit with the longest name is {0}.",longestName);
//輸出結果:
//The fruit with the longest name is PASSIONFRUIT. 

 

5、使用 Aggregate 應用累加器函數和使用種子值

下例使用linq的Aggregate方法統計一個數組中偶數的個數。

 

 
C# 代碼   複製

int[] ints = { 4, 8, 8, 3, 9, 0, 7, 8, 2 };
//統計一個數組中偶數的個數,種子值設置爲0,找到偶數就加1
int numEven = ints.Aggregate(0, (total, next) =>
         next % 2 == 0 ? total + 1 : total);
Console.WriteLine("The number of even integers is: {0}", numEven);
//輸出結果:
//The number of even integers is: 6 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章