首页 > 解决方案 > 如何在 VB.Net 中将数据表列转换为字符串列表

问题描述

我有一个数据表,其中有一列。我想获取该数据表列并将其直接转换为字符串列表。

我尝试使用 For Each 循环来获取每个数据行项并将其写入字符串列表,但是当我在使用 Write Line 后查看输出时,我得到“System.Data.DataRow”而不是行值类似于“11363”。

这是数据表。行标题是“代码”。列标题下方的值是我想要添加到字符串列表中的值。

[Codes
11361
11362
11363
15509
16494
16898
17333
19550
]

这是我尝试使用但对我不起作用的代码。

ForEach row As DataRow in ExampleDataTable
    If Not String.IsNullOrEmpty(row.ToString.Trim)
        ExampleList.Add(row.ToString)
    End If
Next

ForEach item As String in ExampleList
    Console.WriteLine(item)
Next

在使用 For Each 循环打印出列表中的所有内容后,我得到的输出是:

System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow

我希望它输出的是:

11361
11362
11363
15509
16494
16898
17333
19550

谁能帮我解决这个问题?我现在在 Stack Overflow 和 MSDN 上阅读了很多帖子,但我无法弄清楚这一点。

标签: vb.netlistdatatables

解决方案


Jon 可能被否决了,因为该代码无法编译。他忘记了一些事情,例如包括用于迭代的 Rows 集合,并且在检查 null 时,他实际上是在检查行本身,而不是值。

    Dim StrList As New List(Of String)
    For Each DtRow As DataRow In dt.Rows
        If DtRow("ColumnName") IsNot Nothing Then
            StrList.Add(DtRow("ColumnName").ToString)
        End If
    Next

你的问题可能被否决了,因为一个简单的谷歌搜索可能会产生 10 个结果如何做到这一点,现在是 11 个。

这可能会被否决,因为它不是评论,所以可能会投赞成票,因为我需要 4 分才能开始发表评论。


推荐阅读