.net - 将 OrderedDictionary 转换为 Dictionary

如何从 OrderedDictionary 转换至 Dictionary<string, string>以简洁但高效的方式?

情况:

我有一个我无法触及的库,它希望我通过 Dictionary<string, string> .我想建立一个 OrderedDictionary不过,因为顺序在我的代码部分非常重要。所以,我正在使用 OrderedDictionary当需要访问图书馆时,我需要将其转换为 Dictionary<string, string> .

到目前为止我尝试了什么:

var dict = new Dictionary<string, string>();
var enumerator = MyOrderedDictionary.GetEnumerator();
while (enumerator.MoveNext())
{
    dict.Add(enumerator.Key as string, enumerator.Value as string);
}

这里必须有改进的余地。是否有更简洁的方法来执行此转换?有什么性能方面的考虑吗?

我正在使用 .NET 4。

最佳答案

只需对您的代码进行两项改进。首先,您可以使用 foreach 而不是 while。这将隐藏 GetEnumerator 的详细信息。

其次,您可以在目标字典中预先分配所需的空间,因为您知道要复制多少项目。

using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections;

class App
{
  static void Main()
  {
    var myOrderedDictionary = new OrderedDictionary();
    myOrderedDictionary["A"] = "1";
    myOrderedDictionary["B"] = "2";
    myOrderedDictionary["C"] = "3";
    var dict = new Dictionary<string, string>(myOrderedDictionary.Count);
    foreach(DictionaryEntry kvp in myOrderedDictionary)
    {
      dict.Add(kvp.Key as string, kvp.Value as string);
    }
  }

}

另一种方法是使用 LINQ,如果您想要一个新实例,就地转换字典 的字典,而不是填充一些现有的字典:

using System.Linq;
...
var dict = myOrderedDictionary.Cast<DictionaryEntry>()
.ToDictionary(k => (string)k.Key, v=> (string)v.Value);

关于.net - 将 OrderedDictionary 转换为 Dictionary<string, string> 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15692191/

相关文章:

php - 在 TYPO3 Fluid 中显示按年和按月分组的元素列表

php - 如何解码json ajax响应

sql - 桥接表主键或复合/复合键

sql - 从当前 sysdate 中检索最近两年的数据

c# - 在 XSL 中创建空格 ( )

php - XML 中的项目符号 "•"

r - 均值与 fivenum : different results?

xml - 使用 XML 或 JSON 有什么用?

linq - linq可以写Update语句吗?

arrays - @a[-@a..-2] 是什么意思?