Question

I have a string in the format

=key1=value1=key2=value2=key3=value3

I need to convert it to a Dictionary<string,string> for the above mentioned key value pairs. What would be the best way to go about this?

I've tried this:

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

Solution

This can be accomplished with a little Linq:

"=key1=value1=key2=value2=key3=value3"
    .Split('=')                            // Split into an array of strings
    .Skip(1)                               // Skip the first (empty) value
    .Select((v, i) => new { v, i })        // Get value and index
    .GroupBy(x => x.i / 2)                 // Group every pair together
    .ToDictionary(g => g.First().v,        // First item in group is the key
                  g => g.Last().v)         // Last item in group is the value

OTHER TIPS

var dict = new Dictionary<string,string>(); 

var input = str.Split(new [] { '=' },StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<input.Length; i+=2)
{ 
    dict.Add(input[i], input[i+1]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top