OrderedDictionary and Dictionary

后端 未结 1 1195
清歌不尽
清歌不尽 2020-12-01 04:24

I was looking for a way to have my Dictionary enumerate its KeyValuePair in the same order that they were added. Now, Dictionary\'s documentation c

相关标签:
1条回答
  • 2020-12-01 04:37

    You are doing it wrong. You need not only to insert values sequentially into dictionary, but also remove some elements and see how the order has changed after this. The next code demonstrates this:

    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);
    }
    

    prints something similar to (OrderedDictionary is always ordered):

    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
    
    0 讨论(0)
提交回复
热议问题