vb.net DataTable:如何使用行名和列名获取项目值?(VB)

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

DataTable: How to get item value with row name and column name? (VB)

vb.netdatatable

提问by Nicolas

I have a simple DataTablewhere one of the columns contains unique values. For example:

我有一个简单DataTable的列,其中一列包含唯一值。例如:

ColumnName1   ColumnName2
value1        35
value2        44
value3        10

Because I know that value 1, 2 and 3 will always be different one from another, I would like to get a value of this table only using ColumnName2and one of the values of ColumnName1. That would for example be:

因为我知道值 1、2 和 3 总是彼此不同,所以我想仅使用ColumnName2ColumnName1的值之一来获取此表的值。例如,这将是:

searchedValue = DataTable.Rows("value3").Item("ColumnName2) 
'result would be 10

I tried the following examples unsuccessfully:

我尝试了以下示例未成功:

回答by Amiram Korach

Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
     searchedValue = rows(0).Item("ColumnName2") 
End If

With FirstOrDefault:

FirstOrDefault

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
     searchedValue = row.Item("ColumnName2") 
End If

In C#:

在 C# 中:

var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
     searchedValue = row["ColumnName2"];

回答by Stephen Craver

'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next

回答by NetTechie

Try:

尝试:

DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()

(This is C# code. Change this to VB equivalent)

(这是 C# 代码。将其更改为 VB 等效代码)