Friday, 3 July 2009

C# - Array to Dictionary

Recently I needed to convert an Array of DictionaryEntry<object,object> items into a Dictionary<string,string> object. Here is simple code using LINQ and ToDictionary method for doing that with 1 command:
DictionaryEntry<object,object>[] props = GetSomeProperties();
Dictionary<string,string> dict =
props.ToDictionary(de => (de.Key != null) ? de.Key.ToString() :
string.Empty);
de => (de.Value != null) ? de.Value.ToString() :
string.Empty);

Isn't that simple? :)

No comments: