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

前端 未结 9 1230
刺人心
刺人心 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:16

    There is not. However, System.Collections.Specialized.OrderedDictionary should solve most need for it.

    EDIT: Another option is to turn this into a Generic. I haven't tested it but it compiles (C# 6) and should work. However, it will still have the same limitations that Ondrej Petrzilka mentions in comments below.

        public class OrderdDictionary
        {
            public OrderedDictionary UnderlyingCollection { get; } = new OrderedDictionary();
    
            public K this[T key]
            {
                get
                {
                    return (K)UnderlyingCollection[key];
                }
                set
                {
                    UnderlyingCollection[key] = value;
                }
            }
    
            public K this[int index]
            {
                get
                {
                    return (K)UnderlyingCollection[index];
                }
                set
                {
                    UnderlyingCollection[index] = value;
                }
            }
            public ICollection Keys => UnderlyingCollection.Keys.OfType().ToList();
            public ICollection Values => UnderlyingCollection.Values.OfType().ToList();
            public bool IsReadOnly => UnderlyingCollection.IsReadOnly;
            public int Count => UnderlyingCollection.Count;
            public IDictionaryEnumerator GetEnumerator() => UnderlyingCollection.GetEnumerator();
            public void Insert(int index, T key, K value) => UnderlyingCollection.Insert(index, key, value);
            public void RemoveAt(int index) => UnderlyingCollection.RemoveAt(index);
            public bool Contains(T key) => UnderlyingCollection.Contains(key);
            public void Add(T key, K value) => UnderlyingCollection.Add(key, value);
            public void Clear() => UnderlyingCollection.Clear();
            public void Remove(T key) => UnderlyingCollection.Remove(key);
            public void CopyTo(Array array, int index) => UnderlyingCollection.CopyTo(array, index);
        }
    

提交回复
热议问题