Get Array from DataTable

Have you ever wanted to obtain a particular column in a data table as an array?

I am sure you will find this as a common requirement sometimes specially when running SQL queries against data and returning back DataTable in your SqlDataAdapter.Fill() method call.
Use the following to create desired array from a column in DataTable. I am using a String() array, you can customise DataType to suit your requirements.

Private Function GetArrayFromDataTable(dt As DataTable) As String()
     Dim _arr As String() = Nothing
     If Not dt.Rows.Count.Equals(0) Then
        ' Now the magic of one line trick
        _arr = dt.AsEnumberable().[Select](Function(row)  row.Field(Of String)(“Column Name”)).ToArray()
     End If
End Function

That’s it, you got your array of values from a DataTable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s