使用LINQ从数据表组数据 [英] Use LINQ to group data from DataTable

查看:109
本文介绍了使用LINQ从数据表组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个DataTable(列:用户ID,chargetag,负责人)使用LINQ组数据。

I want to use LINQ to group data from a DataTable (columns: userid, chargetag, charge).

内容看起来是这样的:

userid    chargetag    charge
-----------------------------
user1     tag3         100
user2     tag3         100
user3     tag5         250

我需要像这样的结果:

chargetag    count    sum
-------------------------
tag3         2        200
tag5         1        250

这是我迄今为止:

var groupedData = from b in dataTable.AsEnumerable()
                  group b by b.Field<string>("chargetag") into g
                  let count = g.Count()
                  select new
                  {
                      ChargeTag = g.Key,
                      Count = count,
                  };



我可以提取chargetag的名称和它的数量。 ?
我如何将不得不改变LINQ查询来访问的费用的总和,以及

I can extract the name of the chargetag and the number of it. How would I have to change the LINQ query to access the sum of charges as well?

在此先感谢: - )

问候,
凯文

推荐答案

这是很容易 - 只需使用总和对本集团扩展方法。

That's pretty easy - just use the Sum extension method on the group.

var groupedData = from b in dataTable.AsEnumerable()
                  group b by b.Field<string>("chargetag") into g
                  select new
                  {
                      ChargeTag = g.Key,
                      Count = g.Count(),
                      ChargeSum = g.Sum(x => x.Field<int>("charge"))
                  };



(我已经删除了条款这里,因为它是不是真正买你什么)

(I've removed the let clause here as it wasn't really buying you anything.)

现在的可能的效率不高;它最终可能以执行两个聚合操作分组两次。您的可能的解决这个问题就像一个查询延续这样的,如果你真的想要的:

Now that may be inefficient; it may end up grouping twice in order to perform two aggregation operations. You could fix that like with a query continuation like this, if you really wanted:

var groupedData = from b in dataTable.AsEnumerable()
                  group b by b.Field<string>("chargetag") into g
                  select new
                  {
                      ChargeTag = g.Key,
                      List = g.ToList(),
                  } into g
                  select new 
                  {
                      g.ChargeTag,
                      Count = g.List.Count,
                      ChargeSum = g.List.Sum(x => x.Field<int>("charge"))
                  };

或者以子句来代替:

var groupedData = from b in dataTable.AsEnumerable()
                  group b by b.Field<string>("chargetag") into g
                  let list = g.ToList()
                  select new
                  {
                      ChargeTag = g.Key,
                      Count = list.Count,
                      ChargeSum = list.Sum(x => x.Field<int>("charge"))
                  };

这篇关于使用LINQ从数据表组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆