zoukankan      html  css  js  c++  java
  • LINQ 标准的查询操作符 合计操作符 Count()、Sum()、Min()、Max()、Average()和Aggregate()

    合计操作符如Count()、Sum()、Min()、Max()、Average()和Aggregate(),不返回一个序列,而返回一个值。 
    Count()扩展方法返回集合中的项数。下面的Count()方法应用于Racer 的Years 属性,过滤赛手,只返回 
    获得冠军次数超过3 次的赛手:

    private static void QuantifiersCount()
            {
                var racers = from r in Formula1.GetChampions()
                             where r.Years.Count() >= 3  //对集合中的子对象集合操作
                             orderby r.Years.Count() descending
                             select new
                             {
                                 Name = r.FirstName + " " + r.LastName,
                                 TimesChampion = r.Years.Count()
                             };  //匿名对象
    
                foreach (var r in racers)
                {
                    Console.WriteLine("{0} {1}", r.Name, r.TimesChampion);
                }
    
    
            }

    结果如下: 
    Michael Schumacher 7 
    Juan Manuel Fangio 5 
    Alain Prost 4

    Sum()方法汇总序列中的所有数字,返回这些数字的和。

    下面的Sum()用于计算一个国家赢得比赛的总次数。

    首先根据国家,对赛手进行分组,再在新创建的匿名类型中,给Wins 属性赋予某个国家赢得比赛的总次数。和SQL一个道理

    private static void QuantifiersSum()
            {
                var countries = (from c in
                                     from r in Formula1.GetChampions()
                                     group r by r.Country into c  //国家分组 c 来做结果集
                                     select new
                                     {
                                         Country = c.Key,
                                         Wins = (from r1 in c
                                                 select r1.Wins).Sum()// 统计
                                     }
                                 orderby c.Wins descending, c.Country // 夺冠次数降序,国家名升序
                                 select c).Take(5);//取出5个
    
                foreach (var country in countries)
                {
                    Console.WriteLine("{0} {1}", country.Country, country.Wins);
                }
    
            }
     

    根据获得一级方程式冠军的次数,最成功的国家是:
    UK 138
    Germany 91
    Brazil 78
    France 51
    Finland 40

    方法Min()、Max()、Average()和Aggregate()的使用方式与Count()和Sum()相同。

    Min()返回集合中的最小值,

    Max()返回集合中的最大值,

    Average()计算集合中的平均值。

    对于Aggregate()方法,可以传送一个λ表达式,对所有的值进行汇总。

    源于:http://www.cnblogs.com/TerryFeng/archive/2009/10/07/1578823.html



    返回导读目录,阅读更多随笔



    分割线,以下为博客签名:

    软件臭虫情未了
    • 编码一分钟
    • 测试十年功


    随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

  • 相关阅读:
    zoj 3279 线段树 OR 树状数组
    fzu 1962 树状数组 OR 线段树
    hdu 5057 块状链表
    hdu3487 Play with Chain
    bzoj 1588营业额统计(HNOI 2002)
    poj2823 Sliding Window
    poj2828 Buy Tickets
    poj2395 Out of Hay
    poj3667 Hotel
    poj1703 Lost Cows
  • 原文地址:https://www.cnblogs.com/08shiyan/p/2046507.html
Copyright © 2011-2022 走看看