-1

I want to split the datatable into N parts. Lets assume that N = 5.

If the datatable.rows.count is 13, the datatable should split to 3 sets where the:

  • First set has 5 records.
  • Second set has 5 records and
  • Third set has 3 records.

If the datatable.rows.count is 16, the datatable should split to 4 sets, where the:

  • First set has 5 records
  • Second set has 5 records
  • Third set has 5 records and
  • Fourth set has 1 record.

How is it possible ? While searching the web, I got to know that it can achieved like this Split a collection into `n` parts with LINQ?

But I want to do a simple function where the datatable and value of N is passed.

It's confusing to loop inside a loop.

halfer
  • 19,824
  • 17
  • 99
  • 186
Anuya
  • 8,082
  • 49
  • 137
  • 222

2 Answers2

0
'create a dtb for demo
Dim dtbSource As New DataTable("MyDataTable")
dtbSource.Columns.Add("Column1", GetType(String))
dtbSource.Columns.Add("Column2", GetType(String))
dtbSource.Columns.Add("Column3", GetType(String))
dtbSource.Rows.Add("1", "2", "3")
dtbSource.Rows.Add("2", "2", "3")
dtbSource.Rows.Add("3", "2", "3")
dtbSource.Rows.Add("4", "2", "3")
dtbSource.Rows.Add("5", "2", "3")
dtbSource.Rows.Add("6", "2", "3")
dtbSource.Rows.Add("7", "2", "3")
dtbSource.Rows.Add("8", "2", "3")
dtbSource.Rows.Add("9", "2", "3")
dtbSource.Rows.Add("10", "2", "3")
dtbSource.Rows.Add("11", "2", "3")
dtbSource.Rows.Add("12", "2", "3")
dtbSource.Rows.Add("13", "2", "3")
'now split the datatable
Dim n As Integer = 5 'number of rows per datatable
Dim dst As New DataSet("Output")
For i As Integer = 0 To dtbSource.Rows.Count - 1 Step n
  Dim intLastRow As Integer = i + n - 1
  If intLastRow > dtbSource.Rows.Count - 1 Then intLastRow = dtbSource.Rows.Count - 1
  Dim dtbNew As DataTable = dtbSource.Clone 'copy structure of original datatable 
  dtbNew.TableName = dtbSource.TableName & "_" & (i \ n).ToString
  For j As Integer = i To intLastRow
    dtbNew.ImportRow(dtbSource.Rows(j))
  Next j
  dst.Tables.Add(dtbNew)
Next i
'the split datatables are available in dst.Tables
MsgBox(dst.Tables(1).Rows(2).Item(0).ToString) 'table 2, row 3, column 1
SSS
  • 4,807
  • 1
  • 23
  • 44
0

This might helpful for what you want

Dim page As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim data As New DataClasses1DataContext
    Dim m = (From master In data.Masters Select master).Skip(page * 5).Take(5)
    DataGridView1.DataSource = m
    page += 1
End Sub
Afshin
  • 4,197
  • 3
  • 25
  • 34