Are elements in a .NET's Dictionary sequential?
如果我创建这样的字典:
1 2 3 4 5 6 | Dictionary<string, MyClass> dic = new Dictionary<string, MyClass>(); dic.add("z1", val1); dic.add("abc9", val2); dic.add("abc8", val3); dic.add("ABC1", val4); |
所以当我这样做的时候:
1 2 3 | foreach (KeyValuePair<string, MyClass> kvp in dic) { } |
号
是否保证检索这些值:"z1"、"abc9"、"abc8"、"abc1"?
如果我先这样做,会是:"z1","abc8","abc1"吗?
1 | dic.Remove("abc9"); |
来自msdn的编号(Emphasis Mine)
For purposes of enumeration, each item in the dictionary is treated as
aKeyValuePair structure representing a value and its
key. The order in which the items are returned is undefined.
号
如果希望对迭代顺序有更多的控制,您可能需要查看ordereddictionary类。
简短的回答是否定的。订单在
您可能需要登记到
例子:
1 2 3 4 5 6 7 8 9 10 11 12 | OrderedDictionary d = new OrderedDictionary(); d.Add("01","First"); d.Add("02","Second"); d.Add("03","Third"); d.Add("04","Fourth"); d.Add("05","Fifth"); for(int i = 0; i < d.Count; i++) // Print values in order { Console.WriteLine(d[i]); } |
注意,由于一些奇怪的原因,没有通用的
Am I guaranteed to have these values retrieved as such:"z1","abc9","abc8","ABC1"?
号
绝对不是。始终将
从文档中:
For purposes of enumeration, each item in the dictionary is treated as a
KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
号
(强调我的)
如果您需要一个特定的顺序,那么您应该使用一个不同的集合——如果您还需要能够通过键来获取,那么可以与字典结合使用。(例如,维护
不,不能保证元素顺序。此外,它还可以根据IDictionary<…>接口的实际实现而有所不同。