如何将字符串拆分为字典

Ton*_*nyP 34 c# c#-3.0

我有这个字符串

string sx="(colorIndex=3)(font.family=Helvetica)(font.bold=1)";
Run Code Online (Sandbox Code Playgroud)

我正在分裂它

string [] ss=sx.Split(new char[] { '(', ')' },
    StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

而不是那样,我怎么能把结果分成一个Dictionary<string,string>?生成的字典应如下所示:

Key          Value
colorIndex   3
font.family  Helvetica
font.bold    1
Run Code Online (Sandbox Code Playgroud)

Eli*_*sha 75

它可以使用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]);
Run Code Online (Sandbox Code Playgroud)

编辑:无需拆分两次即可获得相同的结果:

Dictionary<string, string> dictionary =
           t.Select(item => item.Split('=')).ToDictionary(s => s[0], s => s[1]);
Run Code Online (Sandbox Code Playgroud)

  • 当然,通过调用t.Select(item => item.Split('=')).ToDictionary(s => s [0],s => s [1]); 类似于@erikkallen和@Luke的答案. (13认同)
  • 有没有办法避免两次调用`s.Split()`? (4认同)

Fre*_*örk 21

可能有更有效的方法,但这应该工作:

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]);
}
Run Code Online (Sandbox Code Playgroud)


Gre*_*con 19

Randal Schwartz有一条经验法则:当你知道自己想要扔掉什么时使用拆分,或者当你知道要保留什么时使用正则表达式.

你知道你想要保留什么:

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

Regex pattern = new Regex(@"\((?<name>.+?)=(?<value>.+?)\)");

var d = new Dictionary<string,string>();
foreach (Match m in pattern.Matches(sx))
  d.Add(m.Groups["name"].Value, m.Groups["value"].Value);
Run Code Online (Sandbox Code Playgroud)

只需一点点努力,您就可以ToDictionary:

var d = Enumerable.ToDictionary(
  Enumerable.Cast<Match>(pattern.Matches(sx)),
  m => m.Groups["name"].Value,
  m => m.Groups["value"].Value);
Run Code Online (Sandbox Code Playgroud)

不确定这看起来是否更好:

var d = Enumerable.Cast<Match>(pattern.Matches(sx)).
  ToDictionary(m => m.Groups["name"].Value,
               m => m.Groups["value"].Value);
Run Code Online (Sandbox Code Playgroud)

  • +1之前从未听过这个规则,但我喜欢它!:) (3认同)

Luk*_*keH 13

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

var dict = sx.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
             .Select(x => x.Split('='))
             .ToDictionary(x => x[0], y => y[1]);
Run Code Online (Sandbox Code Playgroud)


eri*_*len 9

var dict = (from x in s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select new { s = x.Split('=') }).ToDictionary(x => x[0], x => x[1]);
Run Code Online (Sandbox Code Playgroud)