datatable使用groupby进行分组统计

如何在datatable中进行分组,并且计算分组后每组的数量,想了一下,可以使用LINQ来实现datatable分组。代码如下

 

效果

区域    库房          数量
北京---北京仓库---1


北京---上海仓库---1


上海---上海仓库---2

 

DataTable dt = new DataTable("cart");
            DataColumn dc1 = new DataColumn("areaid", Type.GetType("System.String"));
            DataColumn dc2 = new DataColumn("house", Type.GetType("System.String"));
            DataColumn dc3 = new DataColumn("seq", Type.GetType("System.String"));
            DataColumn dc4 = new DataColumn("remark", Type.GetType("System.String"));

            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);


            DataRow dr = dt.NewRow();
            dr["areaid"] = "北京";
            dr["house"] = "北京仓库";
            dr["seq"] = "2";
            dr["remark"] = "货到付款";
            dt.Rows.Add(dr);


            DataRow dr1 = dt.NewRow();
            dr1["areaid"] = "北京";
            dr1["house"] = "上海仓库";
            dr1["seq"] = "1";
            dr1["remark"] = "货到付款";
            dt.Rows.Add(dr1);

            DataRow dr2 = dt.NewRow();
            dr2["areaid"] = "上海";
            dr2["house"] = "上海仓库";
            dr2["seq"] = "1";
            dr2["remark"] = "货到付款";
            dt.Rows.Add(dr2);

            DataRow dr3 = dt.NewRow();
            dr3["areaid"] = "上海";
            dr3["house"] = "北京仓库";
            dr3["seq"] = "1";
            dr3["remark"] = "货到付款";
            dt.Rows.Add(dr3);
            var query = from t in dt.AsEnumerable()
                        group t by new { t1 = t.Field<string>("areaid"), t2 = t.Field<string>("seq") } into m
                        select new
                        {
                            areaid = m.Key.t1,
                            seq = m.Key.t2,
                            house = m.First().Field<string>("house"),
                            rowcount = m.Count()
                        };
            Console.WriteLine("区域 " + "  库房" + "   数量");
            foreach (var item in query.ToList())
            {
                if (item.rowcount > 1)
                {
                    Console.WriteLine(item.areaid + "---" + item.house);
                }
                Console.WriteLine(item.areaid + "---" + item.house + "---" + item.rowcount);
                Console.WriteLine("\r\n");
            }
            Console.ReadKey();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值