weloytty weloytty - 1 year ago 100
Vb.net Question

Populating a List(Of String) from a Datatable using LINQ in VB.NET

So I have a DataTable that looks more or less like

Column 0 | Column 1
Something | Something Else
Another Thing | Another Something Else

And I want to put everything in column 0 into a List(Of String)

I could do

Dim returnValue as List(Of String)
For Each r As DataRow In dt.Rows

But that's old and busted. I want to do

returnValue = (From r In dt.Rows Select DirectCast(r, DataRow).Item(0)).ToList

But that gives me a list(of Object).

How can I directly create a list(of String)

(the DirectCast is there because I have Option Strict On)

Answer Source

It is in an datarow collection so we need to cast it out.


The function in the Select asks which field do you want from the casted object.

returnValue = dt.Rows.Cast(Of DataRow).Select(Function(dr) dr(0).ToString).ToList
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download