1

您如何以简洁但高效的方式从OrderedDictionaryto转换?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。

4

2 回答 2

6

只需对您的代码进行两项改进。首先,您可以使用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);
于 2013-03-28T21:17:32.240 回答
1

如果您改用泛型SortedDictionary<TKey, TValue>,则可以简单地使用Dictionary<TKey, TValue>带有参数的构造IDictionary<TKey, TValue>函数:

var dictionary = new Dictionary<string, string>(MyOrderedDictionary);

注意:您将无法使用同一个类来维护顺序和派生自,Dictionary因为其中的方法Dictionary不是虚拟的。库创建者应该使用IDictionary而不是Dictionary公开公开的库方法,但他们没有,所以现在你必须处理它。

于 2013-03-28T21:13:11.287 回答