Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建字典<;字符串,字符串>;从分隔字符串_C#_String_Dictionary - Fatal编程技术网

C# 创建字典<;字符串,字符串>;从分隔字符串

C# 创建字典<;字符串,字符串>;从分隔字符串,c#,string,dictionary,C#,String,Dictionary,我的应用程序需要使用字符串: "????infoResponse\n\\voip\\1\\g_humanplayers\\1\\g_needpass\\0\\pure\\1\\gametype\\0\\sv_maxclients\\8\\clients\\1\\mapname\\oa_rpg3dm2\\hostname\\test\\protocol\\71" 我正在寻找从这个字符串创建字典的最快解决方案 其中,链中的第一个字符串是键,下一个是值 我试着 但不知道如何将数组转换为字典 现在我有

我的应用程序需要使用字符串:

"????infoResponse\n\\voip\\1\\g_humanplayers\\1\\g_needpass\\0\\pure\\1\\gametype\\0\\sv_maxclients\\8\\clients\\1\\mapname\\oa_rpg3dm2\\hostname\\test\\protocol\\71"
我正在寻找从这个字符串创建
字典
的最快解决方案 其中,链中的第一个字符串是键,下一个是值

我试着

但不知道如何将数组转换为字典

现在我有:

[0]: "voip"
[1]: "1"
[2]: "g_humanplayers"
[3]: "1"
[4]: "g_needpass"
[5]: "0"
[6]: "pure"
[7]: "1"
[8]: "gametype"
[9]: "0"
[10]: "sv_maxclients"
[11]: "8"
[12]: "clients"
[13]: "1"
[14]: "mapname"
[15]: "oa_rpg3dm2"
[16]: "hostname"
[17]: "test"
[18]: "protocol"
[19]: "71"
但我需要密钥和值对:

 voip -> 1 
 g_humanplayers ->1
 g_needpass -> 0 
如何将字符串标记为键和值对?

这是您的字符串

   string str="????infoResponse\n\\voip\\1\\g_humanplayers\\1\\g_needpass\\0\\pure\\1\\gametype\\0\\sv_maxclients\\8\\clients\\1\\mapname\\oa_rpg3dm2\\hostname\\test\\protocol\\71";
这将在单个列表中拆分所有值和键

var list1= str.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
这将创建一对键和值的字典

var  list2 = list1
            .Select((s, i) => new { s, i })
            .GroupBy(x => x.i / 2)
            .ToDictionary(g => g.First().s, g => g.Last().s);
输出

 var g_humanplayers = list2["g_humanplayers"].ToString();
 var g_needpass = list2["g_needpass"].ToString();
g_HumanPlayer存储值1
g_needpass存储值0


查看
ToDictionary
LINQ方法,如果有多个字符串,则使用.Split。另外,您尝试过什么?如果您能以某种方式说出您希望词典的外观,即本例中的键和值,这会有所帮助。例如“g_HumanPlayer\\1\\g_needpass\\0”g_HumanPlayer应该是键,1应该是值g_needpass应该是键,0应该是值
 var g_humanplayers = list2["g_humanplayers"].ToString();
 var g_needpass = list2["g_needpass"].ToString();