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

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

问题描述

我有一个名为DTHead的DataTable,它具有以下记录,

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

这里,我需要拆分上面的DataTable分为三个表,基于MIVID如下:

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手段,那么4 Child DataTable应该基于MIVID创建。如何做到这一点?

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.

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

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