【问题标题】:Generic dictionary that can retain the order of keys by the way they were added可以通过添加键的方式保留键顺序的通用字典
【发布时间】:2018-10-05 18:24:37
【问题描述】:

我正在尝试做这样的事情:

Dictionary dict = Dictionary<string, List<string>>();
dict.Add("someKey1", new List<string>());
dict.Add("orange", new List<string>());
dict.Add("foo", new List<string>());

然后当我遍历键时,我希望它们保留添加时的顺序:

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    Console.WriteLine(entry.Key);
}

应该打印出来:

someKey1
orange
foo

我知道 c# 字典键在添加时不会保留它们的顺序,那么有没有其他方法可以让键保持它们的顺序?

【问题讨论】:

标签: c# dictionary


【解决方案1】:

.NET 中不存在通用有序字典,但您可以改用 OrderedDictionary 类。见MSDN

【讨论】:

  • 这不是通用的。我需要一种方法来在添加键时保持键的顺序,并且还能够创建 List. 类型的值
  • 是的,我确实读过,没有通用的方法,只有OrderedDictionary。否则你必须自己实现它或使用第三方类
【解决方案2】:

使用System.Collections.Generic 中的Queue 类来确保顺序。

// Create queue
Queue<TestItem> queue = new Queue<TestItem>();
// Add item
queue.Enqueue(new TestItem { });
// Fetch item
queue.Dequeue();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2023-02-03
    • 2015-10-21
    • 2023-03-04
    相关资源
    最近更新 更多