zoukankan      html  css  js  c++  java
  • LINQ中的Aggregate语法

    这个语法可以做一些复杂的聚合运算,例如累计求和,累计求乘积。它接受2个参数,一般第一个参数是称为累积数(默认情况下等于第一个值),而第二个代表了下一个值。

    第一次计算之后,计算的结果会替换掉第一个参数,继续参与下一次计算。

    下面是我写的一个简单范例,使用Aggregate语法做阶乘运算。

    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;
    
            }
        }
    }
    
  • 相关阅读:
    Common ThreadView
    经典代码IOCP的C#实现(转)
    Common.UdpLib
    Common.TcpLibTcpServerWIOCP
    Common.TcpLibTcpServerY
    sql中将分隔字符串转为临时表的方法
    病毒及流氓软件自我复制的简单实现
    一句sql搞定个人所得税计算
    财务月度的创建及生成
    box2d 教程
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1638140.html
Copyright © 2011-2022 走看看