在VB.NET中使用LINQ从数据表填充列表(字符串) [英] 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
我想将第0列中的所有内容都放入一个List(Of String)
And I want to put everything in column 0 into a List(Of String)
我可以做到
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)
(DirectCast之所以存在,是因为我严格启用了选项)
(the DirectCast is there because I have Option Strict On)
推荐答案
根据上述Heinzi的回答进行操作.我用它编写了自己的示例,并将在下面发布.这是一个完整的VB程序示例,对于不那么高级的用户可能更好.
Credit to Heinzi's answer above. I used it to code my own example which I will post below. It is a complete VB Program Example which may be better for less advanced users.
我已经测试过并确认它可以正常工作.谢谢!
I have tested it and verified it is working. Thank you!
Sub Main
Dim dataTable1 As New DataTable
Dim listOfString As New List(Of String)
dataTable1.Columns.Add("DT Column Title" , GetType(String))
dataTable1.Rows.Add("1234")
dataTable1.Rows.Add("1235")
dataTable1.Rows.Add("1236")
dataTable1.Rows.Add("1237")
listOfString = (From item In dataTable1.AsEnumerable() Select item.Field(Of String)(0)).ToList()
End Sub
这篇关于在VB.NET中使用LINQ从数据表填充列表(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!