问题
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
returnValue.Add(r.Item(0).ToString)
Next
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)
回答1:
dt.Rows
is from before the time of .NET generics, so it won't return an IEnumerable(Of DataRow)
. However, there is an extension method, DataTable.AsEnumerable, which does exactly what you need:
returnValue = (From r In dt.AsEnumerable() Select r.Field(Of String)(0)).ToList()
Note that my example also uses the DataRow.Field extension method, which allows type-safe access to DataRow fields without needing an explicit cast (even with Option Strict On).
回答2:
It is in an datarow collection so we need to cast it out.
Cast
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
来源:https://stackoverflow.com/questions/30644853/populating-a-listof-string-from-a-datatable-using-linq-in-vb-net