vb.net 在 DataRow 中循环 DataColumns
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10187998/
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
Loop DataColumns in DataRow
提问by Gian
I am converting data table content to string, Say the dataset has 12 rows and 8 column. At the end, the Dict contain 12 rows or 96 columns. what's wrong with my code below, how do I reset the row?
我正在将数据表内容转换为字符串,假设数据集有 12 行和 8 列。最后,Dict 包含 12 行或 96 列。我下面的代码有什么问题,如何重置行?
Tia.
蒂亚。
Dim ds As DataSet = ClsDB.GetDataSet(sql)
If Not ds Is Nothing AndAlso ds.Tables.Count > 0 Then
Dim row As New List(Of KeyValuePair(Of String, String))
Dim dict As New List(Of KeyValuePair(Of Integer, Object))
Dim dt As DataTable = ds.Tables(0)
Dim i As Integer = 0
For Each dr As DataRow In dt.Rows
For Each dc As DataColumn In dt.Columns
row.Add(New KeyValuePair(Of String, String)(dc.ColumnName, IIf(Not IsDBNull(dr.Item(dc.ColumnName)), dr.Item(dc.ColumnName), "")))
Next
dict.Add(New KeyValuePair(Of Integer, Object)(i, row))
i += i
Next
Return New JavaScriptSerializer().Serialize(dict)
Else
Return "No Data"
End If
回答by Jodrell
You should reinitialise row
for every dr
, in fact you needn't declare row
outside the dr
loop.
你应该重新初始化row
每一个dr
,其实你不需要声明row
外dr
循环。
For Each dr As DataRow In dt.Rows
Dim row As New List(Of KeyValuePair(Of String, String)) // <<-
For Each dc As DataColumn In dt.Columns
row.Add(...
Next
dict.Add(...
Next