根据列值将数据表拆分为 2 个或更多数据表 [英] Split a DataTable into 2 or more DataTables based on Column value

查看:30
本文介绍了根据列值将数据表拆分为 2 个或更多数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为DTHead"的数据表,其中包含以下记录,

I have a DataTable called "DTHead" which has the following records,

 MIVID      Quantity         Value
------     ----------       --------
   1           10             3000
   1           20             3500
   1           15             2000
   2           20             3000
   2           50             7500
   3           25             2000

这里,我需要根据MIVID将上面的DataTable拆分成三个表,如下所示;

Here, I need to split the above DataTable into three tables based on the MIVID such as follows;

DTChild1:

  MIVID           Quantity        Value
 -------         ----------     ---------
   1                10             3000
   1                20             3500
   1                15             2000

DTChild2:

  MIVID           Quantity        Value
 -------         ----------     ---------
   2                20             3000
   2                50             7500

DTChild3:

  MIVID           Quantity        Value
 -------         ----------     ---------
    3               25             2000

假设,如果 Header DataTable 包含 4 个不同的 MIVID 手段,那么应该基于 MIVID 创建 4 个 Child DataTable.如何做到这一点?

Suppose, if the Header DataTable contains 4 different MIVID means, then 4 Child DataTable should be created based on the MIVID. How to do this?

推荐答案

使用LINQ to DataTable将第一列按GroupBy分组,并使用方法CopyToDataTable 将行列表复制到 DataTable

Use LINQ to DataTable to group the first column by GroupBy, and use method CopyToDataTable to copy list of rows to DataTable

 List<DataTable> result = DTHead.AsEnumerable()
            .GroupBy(row => row.Field<int>("MIVID"))
            .Select(g => g.CopyToDataTable())
            .ToList();

然后您就可以如您所愿地以数据表列表的形式获得结果.

Then you can get the result as a list of DataTables as you expected.

这篇关于根据列值将数据表拆分为 2 个或更多数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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