2012-07-23 53 views
0

我需要动态地将数据表拆分为多个数据表,并且后续数据表的数量也会有所不同。最终用户将输入一个值,这将确定将从原始数据导出的数据表的数量。例如:用户输入10,原来的dt有20行。将会有10个dt,每个创建2行。但是,如果原始dt有11行,则会创建9行,1行和1行,并创建2行。如何在vb.net中完成此操作而无需对规则进行硬编码?我已经阅读并尝试了下面的帖子,但它仍然没有让我在那里。将数据表拆分为n个数据表

Split a collection into `n` parts with LINQ?

回答

1

您可以使用LINQ的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()) 
+0

Vielen丹科献给戴恩援助组织! @Tim Schmelter - 这个建议非常完美!我没有和LINQ一起工作过很多,你可能有任何书籍建议吗? – user10001110101 2012-07-24 12:29:18

+0

@Tim你介意解释当创建'tables'时最后一部分正在做什么,以及它返回什么格式/数据的样子? – JWiley 2014-12-17 17:59:44

+0

这里是没有使用LINQ的代码的c#和vb.net版本为我工作[分割数据表成块](http://stackoverflow.com/questions/34663933/split-datatable-into-multiple-fixed-sized -tables/43397945#43397945) – 2017-04-13 17:05:16