vb.net 数据表按特定列名循环遍历行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44294542/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:17:43  来源:igfitidea点击:

vb.net datatable loop through rows by specific column name

vb.net

提问by tharun

Hi i am trying to loop through row only in specific column. However i did not succeed, can any one help me. Here is my code, myXvalue = "CPI" is the column header Name.

嗨,我正在尝试仅在特定列中循环遍历行。但是我没有成功,任何人都可以帮助我。这是我的代码,myXvalue = "CPI" 是列标题名称。

Dim myXvalue = "CPI"

 For Each column As DataColumn In dt.Columns


                If column.ColumnName = myXvalue Then

                    For k As Integer = 0 To dt.Rows(myXvalue).Count - 1

                        Console.WriteLine(myXvalue & " === " & dt.Rows(0)(k).ToString)


                    Next

                    Console.ReadKey(True)


                End If

采纳答案by jonathana

a. In visual basic.net a better practice is to define the types of fields or propeties.
use Dim myXvalue As String = "CPI"and not Dim myXvalue = "CPI".
if you familiar with c# this convention is not exactly like varin c#:
Is VB's Dim the same as C#'s var?

一种。在visual basic.net 中,更好的做法是定义字段或属性的类型。
使用Dim myXvalue As String = "CPI"而不是Dim myXvalue = "CPI"
如果您熟悉 c#,则此约定与 c# 中的不完全相同var
VB 的 Dim 与 C# 的 var 相同吗?

b. the code below is one way to achieve what you need.

湾 下面的代码是实现您所需要的一种方法。

Private Sub Func()
    Dim myXvalue As String = "CPI"
    Dim colIndex As Integer = -1

    For i As Integer = 0 To dt.Columns.Count - 1
        If dt.Columns(i).ColumnName = myXvalue Then
            colIndex = i
            Exit For
        End If
    Next

    If colIndex = -1 Then
        ' only for safty if this column name is not exist
        Exit Sub
    End If

    For i As Integer = 0 To dt.Rows.Count - 1
        Console.WriteLine((myXvalue & "===" & dt.Rows(i).Item(colIndex).ToString()))
    Next

    Console.ReadKey(True)
End Sub

回答by Nick Painter

This should do the trick.

这应该可以解决问题。

Dim dt As New DataTable()
For Each dr As DataRow In dt.Rows
    If dr.Item("myColumnHeaderName").ToString = "certainColumnValue" Then
        Console.WriteLine(dr.Item("myColumn").ToString())
    End If
Next

回答by Peter Schneider

With this you get a list of all Items from one Column

有了这个,您可以获得一列中所有项目的列表

Dim col_allitems as string = myData.Rows.Cast(Of DataRow).Select(Function(row) row.Item(1).ToString)