How to split string into a dictionary

房东的猫 提交于 2019-12-20 08:57:17

问题


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

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



回答2:


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:


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.

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:

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



回答4:


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



回答5:


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



回答6:


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



回答7:


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



回答8:


Often used for http query splitting.

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



回答9:


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...

Create a JSON string on the client side either like this:

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.



来源:https://stackoverflow.com/questions/1852200/how-to-split-string-into-a-dictionary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!