在 VB.NET 中使用 LINQ 从数据表填充列表(字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30644853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populating a List(Of String) from a Datatable using LINQ in VB.NET
提问by weloytty
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)
我想将第 0 列中的所有内容放入 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)
(DirectCast 在那里是因为我有 Option Strict On)
回答by OneFineDay
回答by Heinzi
dt.Rowsis 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:
dt.Rows来自 .NET 泛型之前,因此它不会返回IEnumerable(Of DataRow). 但是,有一个扩展方法DataTable.AsEnumerable,它完全符合您的需要:
returnValue = (From r In dt.AsEnumerable() Select r.Field(Of String)(0)).ToList()
Note that my example also uses the DataRow.Fieldextension method, which allows type-safe access to DataRow fields without needing an explicit cast (even with Option Strict On).
请注意,我的示例还使用了DataRow.Field扩展方法,该方法允许对 DataRow 字段进行类型安全的访问,而无需显式转换(即使使用 Option Strict On)。

