简体   繁体   中英

Convert a delimited string to a List of KeyValuePair<string,string> in C#

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?

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]); })

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM