gpt4 book ai didi

c# - OrderedDictionary 和字典

转载 作者:IT王子 更新时间:2023-10-29 03:49:32 27 4
gpt4 key购买 nike

我一直在寻找一种方法来拥有我的 Dictionary枚举其KeyValuePair按照添加它们的顺序。现在,Dictionary's documentation明确指出:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

我发现我需要的是 OrderedDictionary ,但作为怀疑论者,我决定自己尝试一下:

OrderedDictionary od = new OrderedDictionary();
Dictionary<String, String> d = new Dictionary<String, String>();

for (int i = 0; i < 10; i++)
{
od.Add("key" + i, "value" + i);
d.Add("key" + i, "value" + i);
}

System.Console.WriteLine("OrderedDictionary");
foreach (DictionaryEntry de in od) {
System.Console.WriteLine(de.Key + ", " + de.Value);
}

System.Console.WriteLine("Dictionary");
foreach (var tmp in d) {
System.Console.WriteLine(tmp.Key + ", " + tmp.Value);
}

输出:

OrderedDictionary
key0, value0
key1, value1
key2, value2
...

Dictionary
key0, value0
key1, value1
key2, value2
...

如您所见,两者都是有序的,这引发了两个问题:

在这种情况下 Dictionary给出与添加值的顺序不同的顺序?我的第一个foreach循环确保我取回我的 KeyValuePair以相同的顺序,还是我必须使用索引?

最佳答案

你做错了。您不仅需要按顺序将值插入字典,还需要删除一些元素并查看此后顺序如何变化。下一个代码演示了这一点:

OrderedDictionary od = new OrderedDictionary();
Dictionary<String, String> d = new Dictionary<String, String>();
Random r = new Random();

for (int i = 0; i < 10; i++)
{
od.Add("key" + i, "value" + i);
d.Add("key" + i, "value" + i);
if (i % 3 == 0)
{
od.Remove("key" + r.Next(d.Count));
d.Remove("key" + r.Next(d.Count));
}
}

System.Console.WriteLine("OrderedDictionary");
foreach (DictionaryEntry de in od) {
System.Console.WriteLine(de.Key + ", " +de.Value);
}

System.Console.WriteLine("Dictionary");
foreach (var tmp in d) {
System.Console.WriteLine(tmp.Key + ", " + tmp.Value);
}

打印类似于(OrderedDictionary 总是有序的):

OrderedDictionary
key3, value3
key5, value5
key6, value6
key7, value7
key8, value8
key9, value9
Dictionary
key7, value7
key4, value4
key3, value3
key5, value5
key6, value6
key8, value8
key9, value9

关于c# - OrderedDictionary 和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16694182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com