DataTable:如何使用行名和列名获取项目值?(VB) [英] DataTable: How to get item value with row name and column name? (VB)
问题描述
我有一个简单的 DataTable
,其中一列包含唯一值.例如:
I have a simple DataTable
where one of the columns contains unique values. For example:
ColumnName1 ColumnName2
value1 35
value2 44
value3 10
因为我知道值 1、2 和 3 总是彼此不同,所以我想仅使用 ColumnName2 和 列名 1.例如:
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 ColumnName2 and one of the values of ColumnName1. That would for example be:
searchedValue = DataTable.Rows("value3").Item("ColumnName2)
'result would be 10
我尝试了以下示例失败:
I tried the following examples unsuccessfully:
使用 DataTable.Select 方法:返回一个行数组,但我只需要一个
with the DataTable.Select method: returns an array of rows, but I only need one
使用 DataTable.Rows.IndexOf 方法:如果我很好理解,我需要提供整行内容才能使用此方法找到它.
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.
推荐答案
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
searchedValue = rows(0).Item("ColumnName2")
End If
使用 FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
在 C# 中:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
searchedValue = row["ColumnName2"];
这篇关于DataTable:如何使用行名和列名获取项目值?(VB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!