How to insert element in first index in dictionary?

前端 未结 9 1020
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 10:09

Is there a method or technique that allows you to insert an element into a Dictionary guaranteeing that the item is in the first index of t

相关标签:
9条回答
  • 2020-12-17 10:26

    Dictionaries are unordered; elements are meant to be retrieved with a key, whose hash points to its value's location.

    What you might want is a List <KeyValuePair>, whose elements can be inserted into a specific index.

    List<KeyValuePair<string, string>> list = dic.ToList();
    list.Insert(0, new KeyValuePair<string, string>("a", "b"));
    
    foreach(KeyValuePair<string, string> pair in list)
        Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
    
    0 讨论(0)
  • 2020-12-17 10:26

    This is not possible with Dictionary<TKey, TValue> as it presents it's values in an unordered fashion when enumerated. There is SortedDictionary<TKey, TValue> which provides ordering but it does so by using an IComparer<TKey> against the key value directly. Here you want the key to be a String and have ordering based on an int. That is not possible with either of these types.

    I think you'll need to implement a new type with these very specific semantics in them. For example.

    class OrderedMap<TKey, TValue> {
      private readonly Dictionary<TKey, TValue> _map = new Dictionary<TKey, TValue>();
      private readonly List<TKey> _list = new List<TKey>();
    
      public void Add(TKey key, TValue value) {
        if (!_map.ContainsKey(key)) {
          _list.Add(key);
        }
        _map[key] = value;
      }
    
      public void Add(TKey key, TValue value, int index) {
        if (_map.ContainsKey(key)) {
          _list.Remove(key);
        }
        _map[key] = value;
        _list.Insert(index, key);
      }
    
      public TValue GetValue(TKey key) {
        return _map[key];
      }
    
      public IEnumerabe<KeyValuePair<TKey, TValue>> GetItems() {
        foreach (var key in _list) { 
          var value = _map[key];
          yield return new KeyValuePair<TKey, TValue>(key, value);
        }
      }
    }
    

    Note this does come with some non-trivial performance differences over a traditional Dictionary<TKey, TValue>. For example Add and Remove are slower.

    0 讨论(0)
  • 2020-12-17 10:31

    Dictionary<TKey, TValue> is inherently unordered (or rather, the ordering is unpredictable and shouldn't be relied upon). If you want some sort of ordering, you need to use a different type. It's hard to recommend any particular type without knowing more about your requirements.

    0 讨论(0)
  • 2020-12-17 10:33

    I know it is a three years old question. But found a workaround of this problem. It may help someone

    Dictionary<String, String> dic = foo.GetOutput();
    
    dic = (new Dictionary<string, string> {{"key","value"}}).Concat(dic).ToDictionary(k => k.Key, v => v.Value);
    

    This will insert the element in the beginning of dictionary :)

    0 讨论(0)
  • 2020-12-17 10:36

    The Dictionary<TKey,TValue> class does not hold items in an ordered manner, so there is no "first" item.

    There is a SortedDictionary<Tkey,TValue> (.NET 4.0+), which sorts by the key, but again, this is a very vague idea of "first".

    0 讨论(0)
  • 2020-12-17 10:39

    The Dictionary<TKey, TValue> can't be ordered.

    You can try SortedDictionary<TKey, TValue> instead, but that one is ordered by the Key, not by a separate index.

    0 讨论(0)
提交回复
热议问题