For Each Dictionary loop in Index order

两盒软妹~` 提交于 2019-12-18 09:48:14

问题


I have tried my hand using for loop with Dictionary but couldn't really achieve what I want to.

I have a certain variable SomeVariable and on the value of this variable I want my foreach to work. SomeVariable can be 1,2,3 or 4

So lets say SomeVariable is 1 I want to retrieve the last item.value from among the first 3 indexes(0,1,2) inside the SomeCollection.

And if SomeVariable is 2 I want to retrieve the last item.value from among the next 3 indexes(3,4,5) inside the SomeCollection.

And so on...

For Each item As KeyValuePair(Of String, Integer) In SomeCollection
    If SomeVariable = 1 Then
            //....
    ElseIf SwitchCount = 2 Then
           //....
    End If
Next

回答1:


A dictionary has no defined order, so any order you perceive is transient. From MSDN:

The order of the keys in the .KeyCollection is unspecified, but it is the same order as the associated values in the .ValueCollection returned by the Values property.

Trying to use the Keys collection to determine the order shows how it is transient:

Dim myDict As New Dictionary(Of Integer, String)

For n As Int32 = 0 To 8
    myDict.Add(n, "foo")
Next

For n As Int32 = 0 To myDict.Keys.Count - 1
    Console.WriteLine(myDict.Keys(n).ToString)
Next

the output prints 0 - 8, in order, as you might expect. then:

myDict.Remove(5)
myDict.Add(9, "bar")

For n As Int32 = 0 To myDict.Keys.Count - 1
    Console.WriteLine(myDict.Keys(n).ToString)
Next

The output is: 0, 1, 2, 3, 4, 9 (!), 6, 7, 8

As you can see, it reuses old slots. Any code depending on things to be in a certain location will eventually break. The more you add/remove, the more unordered it gets. If you need an order to the Dictionary use SortedDictionary instead.




回答2:


You can't access the dictionary by index but you can access the keys collection by index. You don't need a loop for this at all.

So something like this.

If SomeVariable = 1 Then
    Return SomeCollection(SomeCollection.Keys(2))
ElseIf SomeVariable = 2 Then 
    ...
End If

If it is truly structured you could do this:

Return SomeCollection(SomeCollection.Keys((SomeVariable * 3) - 1))

You probably need some error checking and ensuring that the length of the dictionary is correct but this should put you on the right track.




回答3:


You can always use a generic SortedDictionary, I only use C# so here's my example:

SortedDictionary<int,string> dict = new SortedDictionary<int, string>();

foreach( KeyValuePair<int,string> kvp in dict) { ... }


来源:https://stackoverflow.com/questions/24438019/for-each-dictionary-loop-in-index-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!