2011-02-26 54 views

回答

3

無法保證您可以按順序從Dictionary<TKey, TValue>中檢索元素。如果這是你想要的行爲,只需將其封裝到一個類中:

class DictionaryWithKeysOrderedByInsertion<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { 
    private readonly List<TKey> keys = new List<TKey>(); 
    private readonly Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(); 

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { 
     foreach(var key in keys) { 
      yield return new KeyValuePair(key, dictionary[key])); 
     } 
    } 

    // etc. 
} 
2

字典是無序的,如果你希望他們回來,他們被插入的順序,你可能要考慮通用Queue

2

沒有,字典不具備這樣的功能。

您可以

  1. 使用2層結構和同時插入兩個 - 列表/ LinkedList的存儲順序和字典提供快速查找。
  2. 您可以添加有關插入時間信息存儲在字典中的條目。
相關問題