Generic Key/Value pair collection in that preserves insertion order?

前端 未结 9 1226
刺人心
刺人心 2020-12-09 01:40

I\'m looking for something like a Dictionary however with a guarantee that it preserves insertion order. Since Dictionary is a hashtable, I do not think it does.<

9条回答
  •  自闭症患者
    2020-12-09 02:08

    Code:

    //A SortedDictionary is sorted on the key (not value)
    System.Collections.Generic.SortedDictionary testSortDic = new SortedDictionary();
    
    //Add some values with the keys out of order
    testSortDic.Add("key5", "value 1");
    testSortDic.Add("key3", "value 2");
    testSortDic.Add("key2", "value 3");
    testSortDic.Add("key4", "value 4");
    testSortDic.Add("key1", "value 5"); 
    
    //Display the elements.  
    foreach (KeyValuePair kvp in testSortDic)
    {
        Console.WriteLine("Key = {0}, value = {1}", kvp.Key, kvp.Value);
    }
    

    Output:

    Key = key1, value = value 5
    Key = key2, value = value 3
    Key = key3, value = value 2
    Key = key4, value = value 4
    Key = key5, value = value 1     
    

提交回复
热议问题