2

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

但是,这是不正确的:(

这是一个代码:

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

现在,列表必须有两个元素... -> "first" 和 "first1"

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

4

2 回答 2

9

您正在遍历整个字典并将所有元素添加到列表中。您应该将 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 语句:

listID.Clear()
For Each pair As KeyValuePair(Of String, Integer) In dictionaryID
    If pair.Value = 1 Then
        listID.Add(pair.Key)
    End If
Next
于 2012-12-20T21:08:46.333 回答
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
于 2012-12-20T21:09:01.090 回答