简体   繁体   English

如何将字符串拆分成字典

[英]How to split string into a dictionary

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> ? 取而代之的是,如何将结果拆分为Dictionary<string,string> The resulting dictionary should look like: 生成的字典应如下所示:

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

It can be done using LINQ ToDictionary() extension method: 可以使用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]);

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

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

Randal Schwartz has a rule of thumb : use split when you know what you want to throw away or regular expressions when you know what you want to keep. Randal Schwartz有一个经验法则 :在知道要丢弃的内容时使用split,在知道要保留的内容时使用正则表达式。

You know what you want to keep: 您知道要保留什么:

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

With a little effort, you can do it with ToDictionary : 只需一点努力,您就可以使用ToDictionary做到这ToDictionary

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

Not sure whether this looks nicer: 不知道这看起来是否更好:

var d = Enumerable.Cast<Match>(pattern.Matches(sx)).
  ToDictionary(m => m.Groups["name"].Value,
               m => m.Groups["value"].Value);
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]);
var dict = (from x in s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            select new { s = x.Split('=') }).ToDictionary(x => x[0], x => x[1]);

You can try 你可以试试

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

var keyValuePairs = sx.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(v => v.Split('='))
            .ToDictionary(v => v.First(), v => v.Last());

You could do this with regular expressions: 您可以使用正则表达式执行此操作:

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

Dictionary<string,string> dic = new Dictionary<string,string>();

Regex re = new Regex(@"\(([^=]+)=([^=]+)\)");

foreach(Match m in re.Matches(sx))
{
    dic.Add(m.Groups[1].Value, m.Groups[2].Value);
}

// extract values, to prove correctness of function
foreach(var s in dic)
    Console.WriteLine("{0}={1}", s.Key, s.Value);

Often used for http query splitting. 通常用于http查询拆分。

Usage: Dictionary<string, string> dict = stringToDictionary("userid=abc&password=xyz&retain=false");

public static Dictionary<string, string> stringToDictionary(string line, char stringSplit = '&', char keyValueSplit = '=')
{
    return line.Split(new[] { stringSplit }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { keyValueSplit })).ToDictionary(x => x[0], y => y[1]); ;
}

I am just putting this here for reference... 我只是将其放在这里以供参考...

For ASP.net, if you want to parse a string from the client side into a dictionary this is handy... 对于ASP.net,如果要将客户端的字符串解析为字典,这很方便...

Create a JSON string on the client side either like this: 像这样在客户端创建一个JSON字符串:

var args = "{'A':'1','B':'2','C':'" + varForC + "'}";

or like this: 或像这样:

var args = JSON.stringify(new { 'A':1, 'B':2, 'C':varForC});

or even like this: 甚至像这样:

var obj = {};
obj.A = 1;
obj.B = 2;
obj.C = varForC;
var args = JSON.stringify(obj);

pass it to the server... 传递给服务器...

then parse it on the server side like this: 然后像这样在服务器端解析它:

 JavaScriptSerializer jss = new JavaScriptSerializer();
 Dictionary<String, String> dict = jss.Deserialize<Dictionary<String, String>>(args);

JavaScriptSerializer requires System.Web.Script.Serialization. JavaScriptSerializer需要System.Web.Script.Serialization。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM