【问题标题】:Can we retrieve Dictionary<A,B> elements in the order in which they were inserted?我们可以按插入的顺序检索 Dictionary<A,B> 元素吗?
【发布时间】:2012-08-31 01:26:25
【问题描述】:

我们如何按插入顺序检索Dictionary&lt;A,B&gt; 元素?如果字典不支持这一点,那么我应该使用哪个对象,它给出了字典的行为,但也允许我按照插入的顺序获取元素。

提前致谢:)

【问题讨论】:

    标签: c#


    【解决方案1】:

    不保证您可以按顺序从Dictionary&lt;TKey, TValue&gt; 中检索元素。如果这是您想要的行为,只需将其封装到一个类中:

    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

      【讨论】:

        【解决方案3】:

        不,字典没有这样的功能。

        你可以

        1. 使用 2 个结构并同时插入到这两个结构中 - List/LinkedList 用于存储序列和字典以提供快速查找。
        2. 您可以将有关插入时间的信息添加到存储在字典中的条目中。

        【讨论】:

          猜你喜欢
          • 2013-11-01
          • 2021-04-18
          • 2020-08-22
          • 1970-01-01
          • 2020-01-03
          • 2022-06-27
          • 1970-01-01
          • 2011-01-09
          • 1970-01-01
          相关资源
          最近更新 更多