Please excuse the large content but I wanted to give you a complete example with the most efficient way to get the result you wish.
(I just used web forms sample page with page_load as a way to create this logic for you to easily test and adjust).
public static class MockData
{
public static DataTable GetMockData()
{
var dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]{
new DataColumn("Id",typeof(Int32)),
new DataColumn("Name",typeof(String)),
new DataColumn("ParentId",typeof(Int32))
});
dt.Rows.Add(new object[] { 1, "AA", 0 });
dt.Rows.Add(new object[] { 2, "BB", 1 });
dt.Rows.Add(new object[] { 3, "CC", 1 });
dt.Rows.Add(new object[] { 4, "DD", 1 });
dt.Rows.Add(new object[] { 5, "EE", 0 });
dt.Rows.Add(new object[] { 6, "FF", 5 });
dt.Rows.Add(new object[] { 7, "GG", 5 });
dt.Rows.Add(new object[] { 8, "HH", 0 });
dt.Rows.Add(new object[] { 9, "II", 8 });
return dt;
}
}
public partial class DataTableSplit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var dts = MockData.GetMockData().AsEnumerable().GroupBy(x => x.Field<int>("ParentId"));
DataSet ds = new DataSet();
foreach(IGrouping<int,DataRow> dataGroup in dts)
{
var groupRows = dataGroup.ToList();
DataTable dt = MockData.GetMockData().Clone();
ds.Tables.Add(dt);
dt.TableName = dataGroup.Key.ToString();
groupRows.ToList().ForEach(x => dt.Rows.Add(x.ItemArray));
}
foreach(DataTable dt in ds.Tables)
{
Debug.WriteLine("Table name: " + dt.TableName);
foreach(DataRow dr in dt.Rows)
{
Debug.WriteLine(dr.ItemArray.ToList().Aggregate((current, next)=>current + "," + next));
}
}
}
}
The output is as follows:
Table name: 0
1,AA,0
5,EE,0
8,HH,0
Table name: 1
2,BB,1
3,CC,1
4,DD,1
Table name: 5
6,FF,5
7,GG,5
Table name: 8
9,II,8