How to select DataTable columns with string array 'LINQ'

Mansour_Dalir 2,036 Reputation points
2023-07-06T16:54:51.6866667+00:00

hi I can't choose like (2D Array).

     Dim MyDataTable As New DataTable
        MyDataTable.Columns.Add("A")
        MyDataTable.Columns.Add("B")
        MyDataTable.Columns.Add("C")
        MyDataTable.Rows.Add({"a", "aL2_1", "aL3_1"})
        MyDataTable.Rows.Add({"b", "bL2_1", "bL3_2"})
        MyDataTable.Rows.Add({"a", "aL2_1", "aL3_2"})
        MyDataTable.Rows.Add({"a", "aL2_2", "aL3_1"})
        MyDataTable.Rows.Add({"b", "bL2_1", "bL3_1"})
        MyDataTable.Rows.Add({"c", "cL2_1", "cL3_1"})
        'Is 2D Array
        Dim arrNoProblem = (From row In MyDataTable.AsEnumerable()
                            Select New Object() {row.Item("B"), row.Item("C")}).ToArray()
'______________________________________Problem
        Dim OnlyColumns As String() = {"B", "C"}
         'Is 3D Array
        Dim arrProblem = (From row In MyDataTable.AsEnumerable()
                          Select New Object() {OnlyColumns.Select(Function(h) row.Item(h)).ToArray()}).ToArray()
     ```

Developer technologies VB
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2023-07-07T05:26:54.8966667+00:00

    Maybe this will work:

    Dim arr = (From row In MyDataTable.AsEnumerable()
               Select OnlyColumns.Select(Function(h) row.Item(h)).ToArray).ToArray
    
    2 people found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,381 Reputation points
    2023-07-06T17:13:22.0933333+00:00

    Not sure ...

            Dim table As New DataTable
    
            table.Columns.Add("Col1", GetType(Integer))
            table.Columns.Add("Col2", GetType(String))
            table.Columns.Add("Col3", GetType(String))
    
            table.Rows.Add(25, "Col1 A", "10")
            table.Rows.Add(50, "Col1 B", "50")
            table.Rows.Add(10, "Col1 C", "51")
            table.Rows.Add(21, "Col1 D", "52")
            table.Rows.Add(100, "Col1 E", "11")
            table.Rows.Add(100, "Col1 F", "12")
            table.Rows.Add(100, "Col1 G", "11")
            table.Rows.Add(100, "Col1 H", "12")
    
            Dim ie As IEnumerable
    
            ie = From rw In table.Rows
                  Select New List(Of Object) From {DirectCast(rw, DataRow).Item("Col1"),
                                                   DirectCast(rw, DataRow).Item("Col3")}
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.