使用LINQ解析样式属性集合 [英] Parse style attribute collection using linq
问题描述
我要解析SVG样式属性,这仅仅是一个分隔的字符串,例如
填充:#e2b126;行程:#010101;笔画宽度:0.3177;脑卒中miterLimit分别:10
块引用>
到
词典<字符串,字符串>
,这样我可以对它进行一些处理。
下面是我有什么,由它来完成的工作,但我想它更简洁的使用LINQ投影,似乎无法得到的语法进行。我尝试使用。选择()。ToDictionary等,但没有喜悦。感谢:
属性字符串=填充:#e2b126;行程:#010101;笔画宽度:0.3177;行程miterLimit分别: 10;
变种对= attributes.Split(';')了ToList()。
变种DIC =新词典<字符串,字符串>();
pairs.ForEach(P =>
{
变种对= p.Split(':');
dic.Add(对[0],对[1] );
});
的foreach(在dic.Keys变种K)
{
Console.WriteLine(K ++ DIC [K]);
}
期望的输出:
填写#e2b126
行程#010101
笔划宽度0.3177
中风miterLimit分别10
解决方案请尝试以下
属性字符串=填充:#e2b126;行程:#010101;笔画宽度:0.3177;脑卒中miterLimit分别:10;
VAR地图=属性
.Split(新[] {','},StringSplitOptions.RemoveEmptyEntries)
。选择(X => x.Split(新[] {':' },StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(p值=指p [0],p值=指p [1]);
击穿
第一个
拆分
调用将返回字符串
值,其中每一个条目是在键:值
格式。以下选择
通话将这些条目中的每一个转换成的String []
其中第一个元素是关键,第二个是该值。在ToDictionary
的调用只是明确执行此映射I want to parse an SVG style attribute, which is just a delimited string, e.g.
"fill:#e2b126;stroke:#010101;stroke-width:0.3177;stroke-miterlimit:10"
into a
Dictionary<string,string>
so that I can perform some processing on it.Here's what I have, which does the job, but I'd like to make it neater using a linq projection, just can't seem to get the syntax. I tried using .Select().ToDictionary etc, but no joy. Thanks:
string attributes = "fill:#e2b126;stroke:#010101;stroke-width:0.3177;stroke-miterlimit:10"; var pairs = attributes.Split(';').ToList(); var dic = new Dictionary<string, string>(); pairs.ForEach(p => { var pair = p.Split(':'); dic.Add(pair[0], pair[1]); }); foreach (var k in dic.Keys) { Console.WriteLine(k + " " + dic[k]); }
Expected output:
fill #e2b126 stroke #010101 stroke-width 0.3177 stroke-miterlimit 10
解决方案Try the following
string attributes = "fill:#e2b126;stroke:#010101;stroke-width:0.3177;stroke-miterlimit:10"; var map = attributes .Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Split(new []{':'}, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(p => p[0], p => p[1]);
Breakdown
The first
Split
call will return an array ofString
values where every entry is in thekey:value
format. The followingSelect
call will convert every one of those entries into astring[]
where the first element is the key and the second is the value. TheToDictionary
call just expressly performs this mapping这篇关于使用LINQ解析样式属性集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!