问题:
如何从转换OrderedDictionary到Dictionary<string, string>以简洁,但性能方法?
情况:
我有一个我无法触摸的lib,希望我通过一个Dictionary<string, string>.我想建立一个OrderedDictionary,因为在我的代码中,顺序非常重要.所以,我正在使用它OrderedDictionary,当它到达lib时,我需要将其转换为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);
}
Run Code Online (Sandbox Code Playgroud)
这里必须有改进的余地.有没有更简洁的方式来执行此转换?任何性能考虑?
我正在使用.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用linq的替代方法,如果你想要新的字典实例,而不是填充一些现有的字典,就地转换字典:
using System.Linq;
...
var dict = myOrderedDictionary.Cast<DictionaryEntry>()
.ToDictionary(k => (string)k.Key, v=> (string)v.Value);
Run Code Online (Sandbox Code Playgroud)