I need to dynamically split a datatable into multiple datatables and the number of subsequent datatables will vary. The end user will enter a value and this will determine the number of datatables that will be derived from the original. For example: the user enters 10, the original dt has 20 rows. There will be 10 dt's with 2 rows each created. However, if the original dt has 11 rows, there would be 9 dt's with 1 row and 1 dt with 2 rows created. How can I accomplish this in vb.net without hardcoding a bunch if rules? I have read through and tried the post below but it still does not get me there.
Asked
Active
Viewed 4,431 times
1 Answers
3
You can use LINQ's GroupBy
:
Dim tbl1 = New DataTable
tbl1.Columns.Add("ID", GetType(Int32))
tbl1.Columns.Add("Text", GetType(String))
For rowIndex As Int32 = 1 To 11
tbl1.Rows.Add(rowIndex, "Row " & rowIndex)
Next
Dim tableCount = 10 ' what the user entered '
Dim divisor = tbl1.Rows.Count / tableCount ' needed to identify each group '
Dim tables = tbl1.AsEnumerable().
Select(Function(r, i) New With {.Row = r, .Index = i}).
GroupBy(Function(x) Math.Floor(x.Index / divisor)).
Select(Function(g) g.Select(Function(x) x.Row).CopyToDataTable())

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
Vielen danke für dein hilfe! @Tim Schmelter - This suggestion worked perfectly! I have not worked that much with LINQ, might you have any book suggestions? – user10001110101 Jul 24 '12 at 12:29
-
@Tim do you mind explaining what the last section is doing when it creates `tables`, and what format/the data looks like that it returns? – JWiley Dec 17 '14 at 17:59
-
here is the c# and vb.net version of the code without using LINQ which worked for me [splitt datatable into chunks](http://stackoverflow.com/questions/34663933/split-datatable-into-multiple-fixed-sized-tables/43397945#43397945) – Jeff D Apr 13 '17 at 17:05