C# 如何将字符串拆分为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1852200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split string into a dictionary
提问by TonyP
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:
相反,我怎么能把结果分成一个Dictionary<string,string>
?生成的字典应如下所示:
Key Value
colorIndex 3
font.family Helvetica
font.bold 1
采纳答案by Fredrik M?rk
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]);
}
回答by Elisha
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]);
回答by erikkallen
var dict = (from x in s1.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
select new { s = x.Split('=') }).ToDictionary(x => x[0], x => x[1]);
回答by Sune Rievers
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);
回答by Greg Bacon
RandalSchwartzhas 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
:
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);
回答by LukeH
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]);
回答by Soenhay
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。
回答by androschuk.a
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());
回答by BSalita
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]); ;
}