vb.netselectdatatablestoarray

Using a List to Fetch Columns from a DataTable


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()

Solution

  • 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.