vb.net 数据表到数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8755055/
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
DataTable to ArrayList
提问by Flashidkz
I want to get value from datatable and then store it to the string() arraylist. datatable contain 3 column (columnA | columnB | columnC). I want to get all value from columnB and store it to arraylist.
我想从数据表中获取值,然后将其存储到 string() 数组列表中。数据表包含 3 列(columnA | columnB | columnC)。我想从 columnB 获取所有值并将其存储到 arraylist。
I have try something like this
我尝试过这样的事情
If myTableData.Rows.Count > 0 Then
For i As Integer = 0 To myTableData.Rows.Count - 1
Dim value() As String = myTableData.Rows(i)(1)
Next
End If
but when I compile that code, I got error message like this :
但是当我编译该代码时,我收到如下错误消息:
Unable to cast object of type 'System.String' to type 'System.String[]'
无法将“System.String”类型的对象转换为“System.String[]”类型
please help me.....
请帮我.....
回答by Tim Schmelter
You could do that with LINQ:
你可以用 LINQ 做到这一点:
Dim colBValues = (From row In myTableData Select colB = row(1).ToString).ToList
Or if you prefer the "old-school" way:
或者,如果您更喜欢“老派”方式:
Dim colBValues = New List(Of String)
For Each row As DataRow In myTableData.Rows
colBValues.Add(row(1).ToString)
Next
I've used a List(Of String)
because it's type-safe, therefore you don't need to cast the values everytime. That makes code more readable, more failsafe and faster.
我使用了 aList(Of String)
因为它是类型安全的,因此您不需要每次都转换值。这使得代码更具可读性、更安全和更快。
If you need it as String-Array, you could simply use ToArray:
如果你需要它作为字符串数组,你可以简单地使用ToArray:
Dim colBValues = (From row In myTableData Select colB = row(1).ToString).ToArray
回答by reshma k
Dim a() As String
Dim total As Integer
'Count the number of rows
total = myTableData.Rows.Count - 1
ReDim a(0 To total)
For i = 0 To total
a(i) = myTableData.Rows(i)(1)
Next
回答by nelek
This is really old question, but I'll provide one more variant of answer :
这确实是个老问题,但我将提供另一种答案:
Dim value = myTableData.Rows.OfType(Of DataRow).Select(Function(x) x(1).ToString()).ToArray
So, if You have more than one column
in Your DataTable
You can use x(columnIndex)
instead 1.
因此,如果您column
在 Your You 中有多个,则DataTable
可以使用x(columnIndex)
1。