2016-01-13 82 views
0

我試圖找到一個Dataset特定的記錄,這是通過一個查詢的結果填充,例如:如何在DataSet中查找記錄?

Dim ds As New DataSet 
Dim query = "SELECT * FROM tax ORDER BY id" 
MyAdapter = New MySqlDataAdapter(query, my connection string here) 
MyAdapter.Fill(ds) 

現在我已經另一個Dataset與同桌的,但內容另一個數據庫我試圖獲得該字段hash,這使我可以比較此行hash的所有字段。其實我所做的就是創建這樣一個循環:

If ds.Tables(0).Rows.Count > 0 Then 

    Dim x As Integer = 0 

    For x = 0 To ds.Tables(0).Rows.Count - 1 

     Dim local_hash = ds.Tables(0).Rows(x).Item("hash") 
     Dim web_hash = ds2.Tables(0).Rows(x).Item("hash") 'This is another dataset as I explained in the comment above. 

     If local_hash = web_hash 'compare if the hash is equal 

下面這段代碼不會爲一個明顯的原因的工作,這兩個數據庫的索引是在循環不同,那麼我將永遠找不到hash場指的是數據集上循環的索引。所以我想問問是否有像.Find這樣的方法或其他可以用來避免這種情況的方法。

+0

您的表中沒有主鍵嗎? –

+0

'發現'由什麼?使用'find'的關鍵是什麼? – Moumit

+0

正如我所說的,我想在名爲ds2的Web數據集中找到字段「hash」。和@AlexB。我有一個PK,但它是一個同步工具,所以我有GUID – Dillinger

回答

0

可以從DataTable選擇得到匹配準則行的一組:

Dim dtLocal = ds.Tables(0) 
Dim dtWeb = ds2.Tables(0) 

Dim local_hash As String '?? 
Dim search As String = "Hash = '{0}'" 
For n = 0 To dtLocal.Rows.Count-1 

    local_hash = dtLocal.Rows(n).Item("hash").ToString 

    ' get matching rows 
    Dim webRows = dtWeb.Select(String.Format(search, local_hash)) 

    'iterate matches 
    For Each r As DataRow In webRows 
     ' do wonderful things 
    Next 

Next 

你可能有搜索字符串格式播放,因爲它是不明確的哈希值是什麼。聽起來像字符串。


另一種方法是使用一個或DataView另一個是使用一個DataTable爲「主」和重建使用當前行的「散列」的另一個作爲SQL WHERE子句。從評論的數據視圖的版本是這樣的:

Dim dvW As New DataView(dtWeb, "", "hash", DataViewRowState.CurrentRows) 
For n = 0 To dtLocal.Rows.Count - 1 
    local_hash = dtLocal.Rows(n).Item("hash").ToString 

    ' get matching rows 
    Dim webRows = dvW.FindRows(local_hash) 

    ' iterate matches 
    ' possibly panic if more than one row 
    For Each dvr As DataRowView In webRows 
     ' do wonderful things 
    Next 
Next 

如果使用Find,而不是FindRows,它會返回行的索引。 FindRows會捕獲其他問題,如不止一次使用Guid/Hash。


使用超過400個「大師」的行和4000+「細節」行,只是迭代高手收集信息的ID,每個大約需要同樣多的時間:260ms爲DataTable.Select VS 376來重建表完全與253使用DataView.FindRows

+0

'Select' in a loop is not一個很好的選擇關於表現。 –

+0

我不認爲OP在談論很多行。他/她正在實施一種手工複製形式,它已經*不夠理想。使用WHERE子句來限制自上次運行以來的LastUpdated行,您可以嘗試限制您正在使用的數量。 – Plutonix

+0

我使用DataSet而不是DataTable。 select方法不存在。 – Dillinger