我想在DataTable中找到一个特定的ID,我使用DataView来过滤结果,但是如何知道过滤视图对应的原始表中的哪一行?有任何想法吗?知道我可以使用LINQ,但我认为这不会有帮助吗?
Dim dt As New DataTable
Dim dv As New DataView(dt)
dv.RowFilter = "ID = 123"
If dv.Count = 1 Then
'which datarow in the original datatable is this?
End If
修改
我想避免循环使用DataTable来找到它:
For r As Integer = 0 To dt.Rows.Count - 1
If CInt(dt.Rows(r).Item("ID")) = 123 Then
Debug.WriteLine("Found it at row " + r.ToString)
Exit For
End If
Next
答案 0 :(得分:2)
没有比这更容易的事了:
Dim dr As DataRow = dv(0).Row
http://msdn.microsoft.com/en-us/library/system.data.datarowview.row%28v=VS.100%29.aspx
编辑:根据您的评论,您可以使用以下来获取行的索引
Dim rowIndex As Int32 = -1
For i As Int32 = 0 To dr.Table.Rows.Count - 1
If dr.Table.Rows(i)("ID").Equals(dr("ID")) Then
rowIndex = i
Exit For
End If
Next
或以这种较短的方式:
Dim rowIndex As Int32 = dr.Table.Rows.IndexOf(dr)
http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.indexof.aspx