如何从 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/