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 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值