55

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.

S G
  • 551
  • 1
  • 4
  • 3
  • 6
    This is basically a duplicate of this question: http://stackoverflow.com/questions/776107/best-way-to-convert-query-string-to-dictionary-in-c I suppose you'd have to replace your `;` with `&` before that would work though. – Kevin Stricker Nov 10 '10 at 04:29
  • Possible duplicate of [Convert a delimited string to a dictionary in C#](https://stackoverflow.com/questions/25091071/convert-a-delimited-string-to-a-dictionarystring-uint-in-c-sharp) – Heretic Monkey Mar 02 '19 at 15:16

5 Answers5

110

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
29

Updated Ani's to take in account the semi colon at the end. The where clause will ensure that you have a key and value before creating and entry.

var dictionary = "key1=value1;key2=value2;key3=value3;"
    .Split(';')
    .Select (part  => part.Split('='))
    .Where (part => part.Length == 2)
    .ToDictionary (sp => sp[0], sp => sp[1]);
Bivoauc
  • 853
  • 5
  • 10
20

You could do this using JSON string, for example:

var dic = JsonConvert.DeserializeObject<Dictionary<int, string>>("{'1':'One','2':'Two','3':'Three'}");
Gerardo Garcia
  • 180
  • 1
  • 5
12

Behold the awesome whitespace ignoring, correcting for last value having or not having a semicolon power of regular expressions:

        var dict = Regex.Matches("key1 = value1; key2 = value2 ; key3 = value3", @"\s*(.*?)\s*=\s*(.*?)\s*(;|$)")
        .OfType<Match>()
        .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

But seriously though, Ani deserves props for the .ToDictionary(). I would never have thought of that.

Kevin Stricker
  • 17,178
  • 5
  • 45
  • 71
9

You could write it like this or loop over it to do it yourself. Either way. Ultimately, you're splitting on ; to get the item pairs, then on = to get the key and value.

string input = "key1=value1;key2=value2;key3=value3;";
Dictionary<string, string> dictionary =
    input.TrimEnd(';').Split(';').ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]);

Loop version:

Dictionary<string, string> dictionary = new Dictionary<string, string>();
string[] items = input.TrimEnd(';').Split(';');
foreach (string item in items)
{
    string[] keyValue = item.Split('=');
    dictionary.Add(keyValue[0], keyValue[1]);
}
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246