2016-09-30 47 views
1

DataTable.Select問題

獲取行索引我有這樣查找和DataTable中

| 1 | 2 | 3 | 
|------|------|------| 
| 1966 | 6544 | 1967 | 
| 9560 | 3339 | 4968 | 
| 0 | 9400 | 1765 | 
| 0 | 5479 | 6701 | 

比如我要檢查,如果1966年簡單的數據表已經在列「1」的存在,如果它存在獲得行索引 我目前做這樣

Dim search() As DataRow = table.Select(" '" & i & "' = '" & value & "' ") 
    'where i is a integer from 1 to 3 and value is a biginteger 
    If search.Count > 0 Then 
     'get row index 
    Else 
     Console.WriteLine("not found") 
    End If 

回答

0

除非行索引包含在行本身的值中,否則必須放棄Select方法並使用基於遊標的方法。如果發現匹配,該示例將停止循環:

Dim intTargetIndex As Integer = -1 
Dim intCursor As Integer = 0 

Do Until intCursor = table.Rows.Count OrElse intTargetIndex > -1 

    If table.Rows(intCursor)(0).ToString() = value.ToString() Then 

     intTargetIndex = intCursor 

    End If 

    intCursor += 1 

Loop 
+0

您的代碼工作罰款給我的問題,,但是否它比使用** table.Select **更好?.. @NoAlias – hagant

+0

我猜這將比table.Select方法快一點。首先,它會在找到單個匹配時停止(類似於.Any()和.Count()> 0),其次.IndexOf可能更昂貴。最好的方法是確定兩種方法。 – N0Alias

2

您的查詢代碼試圖查詢號碼領域的字符串,所以如果要查詢的數據表列都是真正INT egers,那麼正確的語法是:

Dim search() As DataRow = table.Select(i.ToString & " = " & value.ToString) 

列名和數字沒有單引號引起它們。然後,要獲取索引,您需要在表中搜索您返回的行的索引。 DataRowCollections有辦法做到這一點,你只需要通過查詢迴歸迭代:

For Each dr As DataRow In table.Select(i.ToString & " = " & value.ToString) 
    MsgBox(dr.Table.Rows.IndexOf(dr).ToString) 
Next dr 
1

使用現有的循環,只是在表中查找該行:

Dim ndx As Int32 
Dim rows = dtSample.Select("Id = 42") 
If rows.Count > 0 Then 
    ndx = dtSample.Rows.IndexOf(rows(0)) 
End If 
Return ndx 

使用擴展方法,你可以凝聚它:

Dim ndx = dtSample.AsEnumerable(). 
       Where(Function(q) q.Field(Of Int32)("Id") = 42). 
       Select(Function(z) dtSample.Rows.IndexOf(z)). 
       ToArray() 

ndx將在這種情況下的陣列,並且將空的時候不存在匹配。

+0

很好地使用IndexOf。 – N0Alias

+0

我仍然不能使用** table.Select ** 'Dim rows = table.Select(「1 = 1966」)'並使用像這樣的條件 ''如果rows.Count> 0然後'@Plutonix – hagant