Better way to convert OrderedDictionary to Dictionary<string, string>
.net, .net-4.0
Solution
Just two improvements to your code. First, you can use `foreach` instead of `while`. This will hide details of GetEnumerator.
Second, you can preallocate required space in the target dictionary, since you know how many items you are going to copy.
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);
}
}
}
An alternative approach is using LINQ, to convert dictionary in-place, if you want a new instance of the dictionary, and not populate some existing one:
using System.Linq;
...
var dict = myOrderedDictionary.Cast<DictionaryEntry>()
.ToDictionary(k => (string)k.Key, v=> (string)v.Value);
Problem
How do you convert from `OrderedDictionary` to `Dictionary<string, string>` in a concise, yet performant way? The Situation: I have a library that I can't touch that expects me to pass a `Dictionary<string, string>`. I want to build up an `OrderedDictionary` though, because order is so important in my part of the code. So, I'm working with an `OrderedDictionary` and when it comes time to hit the library, I need to convert it to `Dictionary<string, string>`. What I have tried so far: ``` var dict = new Dictionary<string, string>(); var enumerator = MyOrderedDictionary.GetEnumerator(); while (enumerator.MoveNext()) { dict.Add(enumerator.Key as string, enumerator.Value as string); } ``` There's got to be room for improvement here. Is there a more concise way of performing this conversion? Any performance considerations? I'm using .NET 4.