linq to sql 学习(7)linq的分组汇总操作

来源:互联网 发布:老虎证券 是人工智能 编辑:程序博客网 时间:2024/05/22 03:23

这里我们主要是介绍LINQ TO SQL 中,分组Group by 在LINQ TO SQL 中的使用。

我们先创建两个cs 类。

    /// <summary>

    /// 手机列表

    /// </summary>

    public class MobileStore

    {

        public string mobId

        { set; get; }

        public string mobName

        { set; get; }

    }

    /// <summary>

    /// 手机销售表

    /// </summary>

    public class MobileSale

    {

        public string Sid

        { set; get; }

        public string mobId

        { set; get; }

        public string mobName

        { set; get; }

        public string price

        { set; get; }

    }

 

 

 

 

 

List<MobileStore> listStore = new List<MobileStore>();

           

listStore.Add(new MobileStore { mobId = "1", mobName = "N86" });

listStore.Add(new MobileStore { mobId = "2", mobName = "N82" });

listStore.Add(new MobileStore { mobId = "3", mobName = "N81" });

listStore.Add(new MobileStore { mobId = "4", mobName = "N95" });

listStore.Add(new MobileStore { mobId = "5", mobName = "N85" });

 

List<MobileSale> listSale = new List<MobileSale>();

listSale.Add(new MobileSale { Sid="1" ,mobId="1",mobName="N86",price="100"});

listSale.Add(new MobileSale { Sid="2", mobId = "2", mobName = "N82",price="220" });

listSale.Add(new MobileSale { Sid="3", mobId = "2", mobName = "N82",price="200" });

listSale.Add(new MobileSale { Sid = "4", mobId = "3", mobName = "N81", price = "300" });

//Sum函数的使用

var querySum =

from  m in listSale group m by m.mobId into g

                       select new

                       {

                           g.Key,

                           总价格= g==null ? 0 : g.Sum(a=>Convert.ToInt32(a.price))

                       };

 

返回的结果:

 

 

 

 

//Max函数的使用

var queryMax = from m in listSale group m by m.mobId into g

                           select new

                           {

                               g.Key,

                               最大价格 = g==null ? 0 : g.Max(a=>Convert.ToInt32(a.price))

                           };

 

 

 

 返回的结果:

 

 

//Min函数的使用

 var queryMin = from m in listSale

                           group m by m.mobId into g

                           select new

                           {

                               g.Key,

                               最小价格 = g == null ? 0 : g.Min(a => Convert.ToInt32(a.price))

                           };

 

 

 

 

 

 返回的结果:

 

//Avg函数的使用

 var queryAvg = from m in listSale

                           group m by m.mobId into g

                           select new

                           {

                               g.Key,

                               平均价格 = g == null ? 0 : g.Average(a => Convert.ToInt32(a.price))

                           };

返回的结果:

 

 

gd.Dataource = queryMin;

gd.DataBind();