Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...