简体   繁体   English

是否可以将字符串拆分成字典?

[英]Is it possible to split a string into a dictionary?

Is it possible to split a string by '&' and init a dictionary in one go or you have to use a string array first? 是否可以通过'&'拆分字符串并一次性创建字典,还是必须先使用字符串数组?

I want to take the url part: 我想参加网址部分:

?a=2&b=3 ?A = 2&B = 3

and load a dictionary<string,string> 并加载dictionary<string,string>

Duplicate of your own question... 您自己的问题重复了...

Best way to take all querystring pairs and init a dictionary 获取所有查询字符串对并初始化字典的最佳方法

As womp said, HttpUtility.ParseQueryString() is your best bet. 正如womp所说,HttpUtility.ParseQueryString()是您最好的选择。

Edit: 编辑:
After doing a little digging I found the following extension method NameValueCollectionExtensions.CopyTo(this NameValueCollection, IDictionary< string, object >) that you could use to populate a true IDictionary. 经过一番挖掘后,我发现了以下扩展方法NameValueCollectionExtensions.CopyTo(this NameValueCollection,IDictionary <string,object>),可用于填充真实的IDictionary。

Based on the format given, I think you want something like this: 根据给定的格式,我认为您需要这样的内容:

var dict = queryString
    .Substring(1) // to skip the "?"
    .Split("&")
    .Select(s => s.Split("="))
    .ToDictionary(sa => sa[0], sa => sa[1]);

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

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