保留插入顺序的通用键/值对集合? [英] Generic Key/Value pair collection in that preserves insertion order?

查看:26
本文介绍了保留插入顺序的通用键/值对集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似字典的东西<K,V>但是保证它保留插入顺序.由于 Dictionary 是一个哈希表,我认为它不是.

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

是否有适用于此的通用集合,或者我是否需要使用旧的 .NET 1.1 集合之一?

Is there a generic collection for this, or do I need to use one of the old .NET 1.1 collections?

推荐答案

没有.但是,System.Collections.Specialized.OrderedDictionary应该可以解决大部分需求.

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

另一种选择是将其转换为泛型.我还没有测试过它,但它可以编译(C# 6)并且应该可以工作.但是,它仍然具有 Ondrej Petrzilka 在下面评论中提到的相同限制.

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<T, K>
    {
        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<T> Keys => UnderlyingCollection.Keys.OfType<T>().ToList();
        public ICollection<K> Values => UnderlyingCollection.Values.OfType<K>().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);
    }

这篇关于保留插入顺序的通用键/值对集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆