zoukankan      html  css  js  c++  java
  • Linq使用Group By

    1.简单形式:
    1. var q =
    2. from p in db.Products
    3. group p by p.CategoryID into g
    4. select g;

    语句描述:Linq使用Group By按CategoryID划分产品。

    说明:from p in db.Products 表示从表中将产品对象取出来。group p by p.CategoryID into g表示对p按CategoryID字段归类。其结果命名为g,一旦重新命名,p的作用域就结束了,所以,最后select时,只能select g。

    2.最大值

    1. var q =
    2. from p in db.Products
    3. group p by p.CategoryID into g
    4. select new {
    5. g.Key,
    6. MaxPrice = g.Max(p => p.UnitPrice)
    7. };

    语句描述:Linq使用Group By和Max查找每个CategoryID的最高单价。

    说明:先按CategoryID归类,判断各个分类产品中单价最大的Products。取出CategoryID值,并把UnitPrice值赋给MaxPrice。

    3.最小值

    1. var q =
    2. from p in db.Products
    3. group p by p.CategoryID into g
    4. select new {
    5. g.Key,
    6. MinPrice = g.Min(p => p.UnitPrice)
    7. };

    语句描述:Linq使用Group By和Min查找每个CategoryID的最低单价。

    说明:先按CategoryID归类,判断各个分类产品中单价最小的Products。取出CategoryID值,并把UnitPrice值赋给MinPrice。

    4.平均值

    1. var q =
    2. from p in db.Products
    3. group p by p.CategoryID into g
    4. select new {
    5. g.Key,
    6. AveragePrice = g.Average(p => p.UnitPrice)
    7. };

    语句描述:Linq使用Group By和Average得到每个CategoryID的平均单价。

    说明:先按CategoryID归类,取出CategoryID值和各个分类产品中单价的平均值。

    5.求和

    1. var q =
    2. from p in db.Products
    3. group p by p.CategoryID into g
    4. select new {
    5. g.Key,
    6. TotalPrice = g.Sum(p => p.UnitPrice)
    7. };

    转载过来的,没什么好说的……

  • 相关阅读:
    算法5--排序
    算法4---数组
    算法3---字符串
    算法2---链表4---单循环链表
    wcf精通1-15
    框架技术细节
    Achieving High Availability and Scalability
    Windows平台下利用APM来做负载均衡方案
    Windows平台分布式架构实践
    web api control注册及重写DefaultHttpControllerSelector、ApiControllerActionSelector、ApiControllerActionInvoker
  • 原文地址:https://www.cnblogs.com/Vam8023/p/5742206.html
Copyright © 2011-2022 走看看