Convert a delimted string to a dictionary in C#

后端 未结 5 629
[愿得一人]
[愿得一人] 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 12: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()
            .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.

提交回复
热议问题