我有这个字符串
string sx="(colorIndex=3)(font.family=Helvetica)(font.bold=1)";
我将它拆分为
string [] ss=sx.Split(new char[] { '(', ')' },
StringSplitOptions.RemoveEmptyEntries);
除此之外,我如何将结果拆分为 Dictionary<string,string>
?这
生成的字典应如下所示:
Key Value
colorIndex 3
font.family Helvetica
font.bold 1
最佳答案
可以使用 LINQ ToDictionary() 扩展方法来完成:
string s1 = "(colorIndex=3)(font.family=Helvicta)(font.bold=1)";
string[] t = s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, string> dictionary =
t.ToDictionary(s => s.Split('=')[0], s => s.Split('=')[1]);
编辑:无需拆分两次即可实现相同的结果:
Dictionary<string, string> dictionary =
t.Select(item => item.Split('=')).ToDictionary(s => s[0], s => s[1]);
关于c# - 如何将字符串拆分为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852200/