如何在Datatable中进行分组 [英] How to do Group by in Datatable

查看:119
本文介绍了如何在Datatable中进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个 DataTable 我希望将一个组应用到它。我该怎么做?



示例:如果第一个id(100)有3条记录而另一个ID(1001)有2条记录;在 DataTable 中,所有记录都在不同的行中出现。如何在 DataTable 上执行分组

Hi,

I have a DataTable and I want to apply a group by to it. How would I do that?

Example: If first id(100) has 3 records and and another ID(1001) has 2 records; in the DataTable all records come through in different rows. How do I do group by on the DataTable?

推荐答案

您不能在 DataTable 内进行分组。您需要在获取数据的查询中执行group by。如果您不能这样做,则需要转换数据,执行分组,然后将其分配回DataTable。以下是如何执行此操作的示例:
You cannot do a group by inside a DataTable. You need to do the group by in the query that gets you the data. If you can't do this, you need to convert your data out, perform the group by and then allocate it back to a DataTable. Here's an example of how to do this:
public DataTable GroupByName(DataTable table)
{
  return table.AsEnumerable().GroupBy(gb => gb.Field<string>("Name")).Select(sel => sel.First()).CopyToDataTable();
}


这篇关于如何在Datatable中进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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