vb.net VB 字典包含值返回键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13980383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB dictionary contains value return key
提问by user1562652
I have a problem... I am trying to put into a list of String dictionary keys values if condition of containsvalue is true:
我有一个问题...如果 containsvalue 的条件为真,我试图将字符串字典键值列表放入:
But, this is not correct :(
但是,这是不正确的:(
here is a code:
这是一个代码:
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
And now, list must have two elements... -> "first" and "first1"
现在,列表必须有两个元素...-> "first" 和 "first1"
Can you help me? Thank you very much!
你能帮助我吗?非常感谢!
回答by Styxxy
You are looping through the whole dictionary and add all the elements to the list. You should put an if statement in the For Each
or use a LINQ query like this:
您正在遍历整个字典并将所有元素添加到列表中。您应该将 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()
Using an if statement:
使用 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
回答by Grinn
My VB.Net is a little rusty, but it looks like you were adding all of them, no matter if their value was 1 or not.
我的 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