对于每个词典循环按索引顺序 [英] For Each Dictionary loop in Index order

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

问题描述

我已尝试使用循环与字典但不能真正实现我想要的手。

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

所以让我们说 SomeVariable 1 我想检索最后一个 item.value SomeCollection 中的前3个索引(0,1,2)。

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.

如果 SomeVariable 2 我想检索最后一个 item.value SomeCollection 之间的接下来的3个索引(3,4,5)中。

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.

等等on ...

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

如您所见,它重用旧插槽。任何代码取决于某个位置的东西最终会破裂。您添加/删除的越多,它获得的无序越多。如果您需要订购词典,请使用 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.

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

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