use*_*652 1 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
Run Code Online (Sandbox Code Playgroud)
现在,列表必须有两个元素... - >"first"和"first1"
你能帮助我吗?非常感谢你!
您循环遍历整个字典并将所有元素添加到列表中.你应该在if中添加一个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()
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)