For Each Dictionary loop in Index order

后端 未结 3 782
一向
一向 2020-12-22 07:41

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

I have a certain variable SomeVariab

3条回答
  •  無奈伤痛
    2020-12-22 08:37

    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.

提交回复
热议问题