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条回答
成全新的幸福
2楼-- · 2020-05-17 02:19

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);
查看更多
我命由我不由天
3楼-- · 2020-05-17 02:27

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楼-- · 2020-05-17 02:28
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楼-- · 2020-05-17 02:36

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());
查看更多
Bombasti
6楼-- · 2020-05-17 02:39

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]); ;
}
查看更多
Melony?
7楼-- · 2020-05-17 02:42

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.

查看更多
登录 后发表回答