Reputation: 646
I have a DataTable
which I populate using a SqlDataAdapter
like this:
Dim dt = New DataTable("Students")
Dim cmd = New SqlCommand("SELECT [Id] ,[Name] FROM [Students]", myADO_SqlConnection)
Dim da = New SqlDataAdapter With {.SelectCommand = cmd}
da.Fill(dt)
In my database, Id
is of type Int
.
I want to get a list of the values in the Id
column. For this I write:
Dim Ids = dt.AsEnumerable.Select(Function(r) r.Item("Id")).ToList
The problem is, that this gives me a List(Of Object)
. Is there a way that I directly get a List(Of Integer)
without casting?
Upvotes: 1
Views: 1045
Reputation: 460288
You can use the DataRow
extension method Field
:
Dim Ids = dt.AsEnumerable.Select(Function(r) r.Field(Of Int32)("Id")).ToList()
This method also supports nullable types, so if a column can be null you can write:
Dim nullableColumnList As List(Of Int32?) = dt.AsEnumerable().
Select(Function(r) r.Field(Of Int32?)("NullableColumnName")).
ToList()
Upvotes: 3