For Each Dictionary 按索引顺序循环 [英] For Each Dictionary loop in Index order

查看:28
本文介绍了For Each Dictionary 按索引顺序循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试将 for 循环与 Dictionary 一起使用,但无法真正实现我想要的.

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

我有一个特定的变量 SomeVariable 并且在这个变量的值上我希望我的 foreach 工作.SomeVariable 可以是 1,2,3 或 4

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

所以假设 SomeVariable1 我想从前 3 个索引(0,1,2) SomeCollection 里面.

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.

如果 SomeVariable2 我想从接下来的 3 个索引(3,4,5) 在 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.

等等……

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

推荐答案

字典没有定义的顺序,因此您感知的任何顺序都是暂时的.来自 MSDN:

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

.KeyCollection 中键的顺序未指定,但与 Values 属性返回的 .ValueCollection 中的关联值的顺序相同.

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.

尝试使用 Keys 集合来确定顺序显示它是如何瞬态的:

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

输出按顺序打印 0 - 8,如您所料.然后:

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

输出为:0, 1, 2, 3, 4, 9 (!), 6, 7, 8

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

如您所见,它重用了旧插槽.任何依赖于某个位置的东西的代码最终都会崩溃.添加/删除的越多,它就越无序.如果您需要对 Dictionary 进行排序,请改用 SortedDictionary.

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.

这篇关于For Each Dictionary 按索引顺序循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆