0

My question is very similar to Convert a delimted string to a dictionary<string,string> in C#, except instead of Dictionary<String, String>, I want List<KeyValuePair<String, String>> (in my case order of those key-value pairs is important)

So, to rephrase my problem:

I have a string in the following format "key1=value1;key2=value2;key3=value3". I need to convert it to a List<KeyValuePair<String, String>> for the above mentioned key value pairs.

I can do this without using LINQ, but can this be done using LINQ? and how?

YogiWatcher
  • 165
  • 1
  • 8

2 Answers2

0

You have to do some tricky stuff with splitting your string. Basically, you need to split by your main delimiter (';') so you end up with: key1=value1, key2=value2, key3=value3. Then, you split each of those by the secondary delimiter ('='). Select that into a new key value pair of strings. It should look similar to this:

var str = "key1=value1;key2=value2;key3=value3";

List<KeyValuePair<string, string>> kvp = str.Split(';')
                                            .Select(x => new KeyValuePair<string, string>
                                                      (x.Split('=')[0], x.Split('=')[1]))
                                            .ToList();

EDIT:

As suggested in comment by Joel Lucsy, you can alter the select to only split once:

.Select(x => { var p = s.Split('='); return new KeyValuePair<string,string>(p[0],p[1]); })
dvo
  • 2,113
  • 1
  • 8
  • 19
  • You could also only do the split once with .Select( x => { var p = s.Split('='); return new KeyValuePair(p[0],p[1]); } ) – Joel Lucsy Sep 11 '19 at 20:16
  • @JoelLucsy Did not know about initialize that temp variable inside the select. That's pretty cool and avoids splitting twice. Great comment! – dvo Sep 11 '19 at 20:20
0

Try to split by semicolon and then split every item by equal sign

"key1=value1;key2=value2;key3=value3"
.Split(';')
.Select(x=>{
   var items=x.Split('=');
   return new KeyValuePair<string,string>(items[0],items[1]);
   })
 .ToList()
Artiom
  • 7,694
  • 3
  • 38
  • 45