Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a DataTable into 2 or more DataTables based on Column value

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

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

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?

like image 824
thevan Avatar asked Oct 05 '12 05:10

thevan


1 Answers

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.

like image 197
cuongle Avatar answered Oct 14 '22 22:10

cuongle