简体   繁体   English

将定界字符串转换为KeyValuePair列表 <string,string> 在C#中

[英]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) 我的问题与在C#中将脱机的字符串转换为Dictionary <string,string>非常相似,除了要使用Dictionary<String, String> ,我要使用List<KeyValuePair<String, String>> (在我的情况下,这些键的顺序是-值对很重要)

So, to rephrase my problem: 因此,重新说明我的问题:

I have a string in the following format "key1=value1;key2=value2;key3=value3" . 我有以下格式的字符串: "key1=value1;key2=value2;key3=value3" I need to convert it to a List<KeyValuePair<String, String>> for the above mentioned key value pairs. 我需要将其转换为上述键值对的List<KeyValuePair<String, String>>

I can do this without using LINQ, but can this be done using LINQ? 我可以不使用LINQ来做到这一点,但是可以使用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 . 基本上,您需要按主定界符( ';' )进行拆分,因此最终得到: key1=value1key2=value2key3=value3 Then, you split each of those by the secondary delimiter ( '=' ). 然后,您用辅助定界符( '=' )分割每一个。 Select that into a new key value pair of strings. Select为新的键值对字符串。 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: Joel Lucsy的评论所建议,您可以将选择更改为仅拆分一次:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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