Using a List to Fetch Columns from a DataTable

805 Views Asked by At

I can fetch columns x1, x2, and x3 from a DataTable (DT) successfully, using e.g.

Dim arrayOfObjects()() As Object = DT.AsEnumerable().Select(Function(b) {b("x1"), b("x2"), b("x3")}).ToArray()

However, most of my fetching will involve different combinations of columns, so in this case I would arrive with a list or string array of column names, and then would prefer to fetch columns based on the list or array. How might that be done? I haven't seen use cases where you can concatenate field names together in a string, and insert that into the Select command to fetch.

I am envisioning using something like

Dim mystr As String = "x1,x2,x3" 

Dim arrayOfObjects()() As Object = DT.AsEnumerable().Select(mystr}).ToArray()
2

There are 2 best solutions below

0
On BEST ANSWER

You can replace:

Dim arrayOfObjects()() As Object = DT.AsEnumerable().Select(Function(b) {b("x1"), b("x2"), b("x3")}).ToArray()

With:

Dim mystr As String = "x1,x2,x3"

Dim tarCols As String() = mystr.Split({","}, StringSplitOptions.RemoveEmptyEntries)

' Shortcut
' Dim tarCols = { "x1", "x2", "x3" }

Dim arrayOfObjects As Object()() = dt.DefaultView.ToTable(False, tarCols).
    AsEnumerable().Select(Function(x) x.ItemArray).ToArray()

To extract the values of any given one or more DataColumn and create that jagged array.

1
On

I created a DataTable and added a few rows in the Form.Load

Cols is a String array of column names that I want in the new DataTable. The magic here is in the .ToTable method documented here MS Docs

Private dt As New DataTable

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    With dt.Columns
        .Add("Number")
        .Add("Name")
        .Add("LastName")
    End With
    dt.Rows.Add({"Mary", "Ruth", "Morrison"})
    dt.Rows.Add("William", "James", "Patrick")
    DataGridView1.DataSource = dt
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Cols = {"Number", "LastName"}
    Dim rows = dt.DefaultView.ToTable(False, Cols)
    DataGridView1.DataSource = rows
End Sub