从数据表填充数组

时间:2013-12-16 16:39:13

标签: arrays vb.net datatable

到目前为止我有这个代码:

Dim arrayOfResults As UInteger()
Dim dt As DataTable
Dim r As DataRow

For i = 0 To dt.Rows.Count - 1


Next

我不知道要在for循环中放什么,我需要访问每行的数据表的第一列并将其存储到数组中。那会是这样的吗?

for loop

    arrayOfResults.? = dt.Rows(i)("Mat")
next

2 个答案:

答案 0 :(得分:3)

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

或者:

Dim dt As DataTable = '...
Dim arrayOfResults() As UInteger = dt.AsEnumerable().Select(Function(r) CUInt(r("Mat"))).ToArray()

或者:

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

答案 1 :(得分:1)

有更好的方法可以做到这一点(特别是LINQ),但为了使它与你正在做的最接近,我会使用通用列表而不是数组(像这样):

Dim ArrayOfResults as New List(Of UInteger)

....

For i = 0 to dt.Rows.Count - 1
   ArrayOfResults.Add(dt.Rows(i)("Mat")
Next 

或者在你知道DataTable中有多少行之后你必须对阵列进行ReDim,然后你可以做一些像:

For i = 0 to dt.Rows.Count - 1
  ArrayOfResult(i) = dt.Rows(i)("Mat")
Next 

但是,正如我所说,数组必须首先适当确定尺寸

希望这至少有点帮助...