Convert a delimted string to a dictionary in C#

后端 未结 5 627
[愿得一人]
[愿得一人] 2020-12-24 11:30

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 wou

5条回答
  •  悲哀的现实
    2020-12-24 11:56

    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 dictionary =
        input.TrimEnd(';').Split(';').ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]);
    

    Loop version:

    Dictionary dictionary = new Dictionary();
    string[] items = input.TrimEnd(';').Split(';');
    foreach (string item in items)
    {
        string[] keyValue = item.Split('=');
        dictionary.Add(keyValue[0], keyValue[1]);
    }
    

提交回复
热议问题