2017-07-17 14 views
1

我需要遍歷一個表並檢查是否有4行含有1 - 4值的特定列。對於循環 - 某些情況我努力尋找邏輯

表格示例:

| cty | st | val |

| 03 | 23 | 1 |

| 03 | 23 | 2 |

| 03 | 23 | 3 |

| 03 | 23 | 4 |

我需要檢查列val是否包含1 - 4值。該表總是按val ASC排序,但該表可能並不總是包含全部4個值。如果1 - 4不在此表中,我需要向用戶發出錯誤消息。 (不是問題)。

我的問題是檢查這一點的循環邏輯。

我已經嘗試了幾種不同的方式,這是我目前所得到的,並不完全得到我要找的東西。

For i As Integer = 1 To 4 Step 1 
    For Each dr As DataRow In dt.Rows 

     'if not all 4 growing season per county are entered, show error message 
     If i <> dr("grows") Then 

      FillErrorResultObject("ERROR00139", "", "", strCountyName, "", "", "", "", "", dtErrorTable, objErrorResult) 
      blnError = True 
      Exit For 

     End If 

    Next 
    If blnError = True Then Exit For 
Next 

****編輯 - 我的示例表中的'val'與代碼示例中'grow'的列相同。想想我會保持原樣,只是添加此評論。

+0

難道這不就是'如果博士(「增長」)<0或博士(「增長」)> 4然後錯誤...'?擺脫'我'循環。 – LarsTech

+0

我需要確保增長具有所有的值1,2,3,4。如果我只有1和2,或者1,2和3等,這個語句不會出錯。 – madmike

回答

2

由於您需要知道表中是否存在所有四個值,您需要跟蹤這四個值以確定它們是否存在。你可以使用這樣的字典:

Dim d As New Dictionary(Of Integer, Boolean) 
For i As Integer = 1 To 4 
    d.Add(i, False) 
Next 

For Each dr As DataRow In dt.Rows 
    Dim v As Integer = Convert.ToInt32(dr("Grows")) 
    If d.ContainsKey(v) Then 
    d(v) = True 
    End If 
Next 

Dim showError As Boolean = False 
For Each kvp As KeyValuePair(Of Integer, Boolean) In d 
    If Not kvp.Value Then 
    showError = True 
    End If 
Next 
If showError Then 
    MessageBox.Show("Error") 
End If 
+0

謝謝。正是我需要的東西,像魅力一樣工作。我以前從未使用過字典。 – madmike