我有一个简单的DataTable
,其中一列包含唯一值。例如:
ColumnName1 ColumnName2
value1 35
value2 44
value3 10
因为我知道值1,2和3总是彼此不同,所以我想只使用 ColumnName2 和中的一个值得到此表的值ColumnName1 。 那将是例如:
searchedValue = DataTable.Rows("value3").Item("ColumnName2)
'result would be 10
我尝试了以下示例失败:
with the DataTable.Select method:返回行数组,但我只需要一行
with the DataTable.Rows.IndexOf method:如果我理解得很好,我需要提供整行内容,以便用这种方法找到它。
答案 0 :(得分:48)
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"];
答案 1 :(得分:1)
'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
答案 2 :(得分:-1)
For i = 0 To dt.Rows.Count - 1
ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)
Next
答案 3 :(得分:-3)
尝试:
DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()
(这是C#代码。将其改为VB等价物)