循环遍历datatable以创建一个看起来像这样的字符串

时间:2011-02-23 22:00:42

标签: asp.net vb.net

我想循环遍历名为SDESCR的数据表列并创建一个看起来像这样的字符串。

Dim labels As String() = {"North", "South", "East", "West", "Up", "Down"}

这就是我正在尝试而且它无法正常工作

Dim labels As String() 
For Each row As DataRow In tablegraph.Rows
            labels = labels " ' " + row.Item("SDESCR") + " ',"
        Next row

感谢您的帮助,我将在明天测试它们,看看哪种方式最好并且标记一个正确。

6 个答案:

答案 0 :(得分:2)

改为

Dim labels As String()
Dim labelsList As List(Of String) = New List(Of String)
For Each row As DataRow In tablegraph.Rows
  labelsList.Add(row.Item("SDESCR"))
Next

labels = labelsList.ToArray()

如果您需要将其作为逗号分隔列表,则可以执行

Dim commaLabels As String = String.Join(labels, ",")

答案 1 :(得分:1)

如果需要将它们存储在数组中,则可以将它们添加到列表中,然后在列表中调用ToArray()方法:

    Dim labelList As New List(Of String)
    For Each row As DataRow In tablegraph.Rows
        labelList.Add(row.Item("SDESCR"))
    Next row

    Dim labels As String() = labelList.ToArray()

答案 2 :(得分:1)

如果您指的是String-Array而不是String,则可以使用:

Dim labels(tablegraph.Rows.Count - 1) As String
For i As Int32 = 0 To tablegraph.Rows.Count - 1
    labels(i) = tablegraph(i)("SDESCR").ToString
Next

如果您希望用逗号分隔它们,可以使用StringBuilder追加:

 Dim labels As New System.Text.StringBuilder
 For i As Int32 = 0 To tablegraph.Rows.Count - 1
     labels.Append(" ' ").Append(tablegraph(i)("SDESCR").ToString).Append(" ',")
 Next
 If labels.Length <> 0 Then labels.Length -= 1 'remove last comma'
 Dim labelString As String = labels.ToString 

答案 3 :(得分:1)

如果你想要一个字符串,请使用它(字符串构建器最好是由于常量字符串声明的内存管理问题。

Dim labels As New StringBuilder()
For Each row As DataRow In tablegraph.Rows
            labels.Append(" ' " + row.Item("SDESCR") + " ',")
        Next row

然后当你需要字符串时,使用labels.ToString()

如果你想要一个数组,请使用这个......

Dim labels As New List(Of String)()
For Each row As DataRow In tablegraph.Rows
            labels.Add(row.Item("SDESCR"))
        Next row

然后当你需要数组时,使用labels.ToArray()

上述代码失败的主要原因是您声明了一个字符串数组。

答案 4 :(得分:1)

有很多方法可以做到这一点;这是一种使用LINQ

的方法
Dim labels As String() = (From myRow In tablegraph _
                          Select CType(myRow.Item("SDESCR"), String)).ToArray
  • 对于“SDESCR”的NULL / NOTHING值,这将失败是没有价值的。

如果您只想要一个以逗号分隔的值,则可以执行以下操作:

Dim sOutput = String.Join(",", (From myRow In tablegraph _
                                Select CType(myRow.Item("SDESCR"), String)).ToArray)

答案 5 :(得分:0)

labels = labels " ' " + row.Item("SDESCR") + " ',"
               ^

加号失踪? 此外,当您执行此操作时,您将在字符串末尾留下额外的,。所以你要把它剥掉。