Subin
Subin

Reputation: 89

Split datatable to multiple tables based on condition

I have a Datatable like this

Id Name ParentId


1         AA        0
2         BB        1
3         CC2       1
4         DD        1           
5         EE        0
6         FF        5
7         GG        5 
8         HH        0     
9         II        8 

I want to split the datatable Like this

Id Name ParentId


2         BB        1
3         CC2       1
4         DD        1        



Id        Name     ParentId    

6         FF        5
7         GG        5     

Id Name ParentId


9         II        8

the spliting is based on the rows BETWEEN the parentId ='0'

Help me pls.. Thank you

Upvotes: 1

Views: 689

Answers (1)

Mark Tomlinson
Mark Tomlinson

Reputation: 127

Use the enumerable with the group by. You will get a table of the 0 items but just throw it away/skip it. The Copy will create the individual data tables within the list that will hold the separate tables you need.

List<DataTable> subTables = dt.AsEnumerable().GroupBy(row => row.Field<int>("ParentId")).Select(g => g.CopyToDataTable()).ToList();

Upvotes: 1

Related Questions