How to split string into a dictionary

2020-05-17 02:13发布

I have this string

string sx="(colorIndex=3)(font.family=Helvetica)(font.bold=1)";

and am splitting it with

string [] ss=sx.Split(new char[] { '(', ')' },
    StringSplitOptions.RemoveEmptyEntries);

Instead of that, how could I split the result into a Dictionary<string,string>? The resulting dictionary should look like:

Key          Value
colorIndex   3
font.family  Helvetica
font.bold    1

标签: c# c#-3.0
9条回答
Root(大扎)
2楼-- · 2020-05-17 02:43

It can be done using LINQ ToDictionary() extension method:

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]);

EDIT: The same result can be achieved without splitting twice:

Dictionary<string, string> dictionary =
           t.Select(item => item.Split('=')).ToDictionary(s => s[0], s => s[1]);
查看更多
成全新的幸福
3楼-- · 2020-05-17 02:43

There may be more efficient ways, but this should work:

string sx = "(colorIndex=3)(font.family=Helvicta)(font.bold=1)";

var items = sx.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Split(new[] { '=' }));

Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (var item in items)
{
    dict.Add(item[0], item[1]);
}
查看更多
家丑人穷心不美
4楼-- · 2020-05-17 02:45
var dict = (from x in s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select new { s = x.Split('=') }).ToDictionary(x => x[0], x => x[1]);
查看更多
登录 后发表回答