VB字典包含值返回键

时间:2012-12-20 20:59:59

标签: vb.net dictionary key contains

我有问题...... 如果containsvalue的条件为真,我试图放入一个String字典键值列表:

但是,这不正确:(

这是一个代码:

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

现在,列表必须有两个元素... - > “第一”和“第一”

你能帮帮我吗? 非常感谢你!

3 个答案:

答案 0 :(得分:7)

您循环遍历整个字典并将所有元素添加到列表中。您应该在For Each中放置一个if语句,或者使用这样的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

答案 1 :(得分: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

答案 2 :(得分:0)

Private dictionaryID As New Dictionary(Of String, Integer)

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

Private listID As New List(Of String)(dictionaryID)

列表部分。