vb.net 从数据表填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20615987/
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
Filling an array from a datatable
提问by bbesase
I have this code so far:
到目前为止我有这个代码:
Dim arrayOfResults As UInteger()
Dim dt As DataTable
Dim r As DataRow
For i = 0 To dt.Rows.Count - 1
Next
I don't know what to put inside the for loop, I need to access the first column of the datatable for each row and store that into the array. So would it be something like this?
我不知道在 for 循环中放什么,我需要访问每一行数据表的第一列并将其存储到数组中。那么它会是这样的吗?
for loop
arrayOfResults.? = dt.Rows(i)("Mat")
next
回答by Joel Coehoorn
Dim dt As DataTable = '...
Dim arrayOfResults As UInteger(dt.Rows.Count - 1)
For i = 0 To dt.Rows.Count - 1
arrayOfResults(i) = CUInt(dt.Rows(i)("Mat"))
Next
Or:
或者:
Dim dt As DataTable = '...
Dim arrayOfResults() As UInteger = dt.AsEnumerable().Select(Function(r) CUInt(r("Mat"))).ToArray()
Or:
或者:
Dim dt As DataTable = '...
Dim results As New List(Of UInteger)(dt.Rows.Count)
For Each row As IDataRecord In dt
results.Add(CUInt(row("Mat")))
Next row
回答by John Bustos
There are substantially better ways to do this (especially LINQ), but to keep it closest to what you were doing, I would either use a generic list rather than an array (Like This):
有更好的方法来做到这一点(尤其是 LINQ),但为了让它最接近你正在做的事情,我要么使用通用列表而不是数组(像这样):
Dim ArrayOfResults as New List(Of UInteger)
....
For i = 0 to dt.Rows.Count - 1
ArrayOfResults.Add(dt.Rows(i)("Mat")
Next
Or you'd have to ReDim the Array after you know how many rows you have in your DataTable and then you could do somethign like:
或者,在知道 DataTable 中有多少行之后,您必须重新调整数组,然后您可以执行以下操作:
For i = 0 to dt.Rows.Count - 1
ArrayOfResult(i) = dt.Rows(i)("Mat")
Next
But, as I said, an array would have to be properly dimensioned first
但是,正如我所说,必须首先正确地确定数组的大小
Hope this helps at least a bit...
希望这至少有一点帮助......

