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
DataTable: How to get item value with row name and column name? (VB)
提问by Nicolas
I have a simple DataTable
where 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 总是彼此不同,所以我想仅使用ColumnName2和ColumnName1的值之一来获取此表的值。例如,这将是:
searchedValue = DataTable.Rows("value3").Item("ColumnName2)
'result would be 10
I tried the following examples unsuccessfully:
我尝试了以下示例未成功:
with the DataTable.Select method: returns an array of rows, but I only need one
with the DataTable.Rows.IndexOf method: if I understood well, I need to provide the whole row contents for it to be found with this method.
使用 DataTable.Select 方法:返回一个行数组,但我只需要一个
使用 DataTable.Rows.IndexOf 方法:如果我理解得很好,我需要提供整行内容,以便使用此方法找到它。
回答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 等效代码)