Convert a delimted string to a dictionary<string,string> in C#

S G picture S G · Nov 10, 2010 · Viewed 61.8k times · Source

I have a string of the format "key1=value1;key2=value2;key3=value3;"

I need to convert it to a dictionary for the above mentioned key value pairs.

What would be the best way to go about this? Thanks.

Answer

Ani picture Ani · Nov 10, 2010

Something like this?

var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
               .Select(part => part.Split('='))
               .ToDictionary(split => split[0], split => split[1]);

Of course, this will fail if the assumptions aren't met. For example, an IndexOutOfRangeException could be thrown if the text isn't in the right format and an ArgumentException will be thrown if there are duplicate keys. Each of these scenarios will require different modifications. If redundant white-space could be present, you may need some string.Trim calls as necessary.