2012-12-20 116 views
1

我有一個問題... 我試圖投入字符串字典鍵的值的列表,如果containsvalue和的條件爲真:VB字典包含的值返回鍵

但是,這是不正確的:(

這裏是一個代碼:

Private listID As New List(Of String)      ' declaration of list 
Private dictionaryID As New Dictionary(Of String, Integer) ' declaration of dictionary 

    'put a keys and values to dictionary 
    dictionaryID.Add("first", 1) 
    dictionaryID.Add("second", 2) 
    dictionaryID.Add("first1", 1) 


    If dictionaryID.ContainsValue(1) Then     ' if value of dictinary is 1 
     Dim pair As KeyValuePair(Of String, Integer) 
     listID.Clear() 
     For Each pair In dictionaryID 
      listID.Add(pair.Key) 
     Next 
    End If 

而現在,名單必須具備兩個要素 - > 「第一」 和 「first1」

你能幫我?非常感謝!

+0

但是你循環了整個詞典,它有2個元素,爲什麼只有一個結果? –

+1

目前還不清楚哪些功能沒有按預期工作。 –

回答

6

您正在遍歷整個字典並將所有元素添加到列表中。你應該把一個if語句中For Each或使用LINQ查詢是這樣的:

If listID IsNot Nothing Then 
    listID.Clear() 
End If 
listID = (From kp As KeyValuePair(Of String, Integer) In dictionaryID 
      Where kp.Value = 1 
      Select kp.Key).ToList() 

使用if語句:

Dim pair As KeyValuePair(Of String, Integer) 
listID.Clear() 
For Each pair In dictionaryID 
    If pair.Value = 1 Then 
     listID.Add(pair.Key) 
    End If 
Next 
+0

非常感謝...現在它工作! – user1562652

1

我VB.Net是有點生疏,但它看起來像你無論它們的值是否爲1,都將它們全部添加。

Private listID As New List(Of String)      ' declaration of list 
Private dictionaryID As New Dictionary(Of String, Integer) ' declaration of dictionary 

    'put a keys and values to dictionary 
    dictionaryID.Add("first", 1) 
    dictionaryID.Add("second", 2) 
    dictionaryID.Add("first1", 1) 


    If dictionaryID.ContainsValue(1) Then     ' if value of dictinary is 1 
     Dim pair As KeyValuePair(Of String, Integer) 
     listID.Clear() 
     For Each pair In dictionaryID 
      If pair.Value = 1 Then 
       listID.Add(pair.Key) 
      End If 
     Next 
    End If 
+0

感謝您的回覆! – user1562652

相關問題