c# - 如何将字符串拆分为字典

标签 c# c#-3.0

我有这个字符串

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/

相关文章:

c# - 将 ASP.NET MVC 应用程序发布到 Web 主机 - 在 VS 项目结构而不是应用程序中部署文件

c# - 返回 XDocument 深处的元素值

c# - 使用 Linq.Expressions.Expression 排序

c# - 我可以更改表单控件值但不触发事件吗?

asp.net - 导出Excel前添加标题

ASP.NET 键/值列表

c# - 将普通类转换为 Web 服务类时出现 System.NotSupportedException 的原因

c#-3.0 - 为什么我不能用 Moq 模拟 MouseButtonEventArgs.GetPosition()?

c# - 如何在特定时间(例如 3 秒)内在标签上显示文本?

c# - 告诉 Json.Net 在序列化对象时编写单引号而不是双引号