2014-11-08 44 views
-2

我發現了一些代碼來保存我的變量作爲字典類型,但是我無法執行搜索。我嘗試了不同的事情並得到了不同的錯誤我的變量是:無法在字典中搜索

Public controlList As New List(Of Dictionary(Of String, String))() 

如何在本字典中搜索項目?

編輯:我創建了一個名爲模塊這GlobalVariables變量,我試圖把它從一個類ControlAdderClass

,我試圖代碼之一:

For i As Integer = 0 To controlList.Count - 1 
    Dim value As Dictionary(Of String, String) = controlList(i) 
    Try 
     MessageBox.Show(controlList(i), Str(value)) 
    Catch 
     Console.WriteLine("Error") 
    End Try 
Next 

,這給了我這個錯誤好幾次:

A first chance exception of type 'System.InvalidCastException' occurred in mirc_dialog.exe
+0

那你試試?有什麼錯誤?此外,你有一個詞典列表,而不僅僅是一個。你究竟在尋找什麼? – Cameron 2014-11-08 06:17:17

+0

看起來你應該做一個自定義的類對象,並做出了一個列表。 – OneFineDay 2014-11-08 06:19:35

+0

不,此代碼僅在模塊中。我想創建全局變量。 – nikel 2014-11-08 06:20:38

回答

1

問題

您應該做的第一件事是設置option strict on。完成後,VS就會因錯誤的下面一行:

MessageBox.Show(controlList(i), Str(value)) 

,出現以下錯誤信息:

重載決策失敗,因爲沒有可訪問「顯示」可以用這些參數來調用。

MessageBox類不具有Show方法的接受Dictionary(Of String, String)等的過載:

Public Shared Function Show(text As Dictionary(Of String, String), caption As String) As DialogResult 

無可選嚴格上,VS選擇所述第一過載的匹配參數的個數。在你的情況下,它this overload

Public Shared Function Show(owner As IWin32Window, text As String) As DialogResult 

而且觀察到,你不能投了字典的IWin32Window。


解決方案

「我怎麼可以搜索本詞典的項目?」

嗯,這裏是一個簡單的例子:

Dim keyToFind As String = "a_key" 
Dim valueToFind As String = "some_value" 

For Each dictionary As Dictionary(Of String, String) In GlobalVariables.ControlList 
    For Each pair As KeyValuePair(Of String, String) In dictionary 

     Dim keyMatched As Boolean = (String.Compare(pair.Key, keyToFind, False) = 0) 
     Dim valueMatched As Boolean = (String.Compare(pair.Value, valueToFind, False) = 0) 

     If (keyMatched AndAlso valueMatched) Then 
      MessageBox.Show(String.Format("Key={0}, Value={1}", pair.Key, pair.Value), "Found") 
     ElseIf (keyMatched) Then 
      MessageBox.Show(String.Format("Key={0}", pair.Key), "Found") 
     ElseIf (valueMatched) Then 
      MessageBox.Show(String.Format("Value={1}", pair.Value), "Found") 
     End If 

    Next 
Next 
+0

感謝您提供詳細的答案和解決方案 – nikel 2014-11-09 03:01:52