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 of String
values where every entry is in the key:value
format. The following Select
call will convert every one of those entries into a string[]
where the first element is the key and the second is the value. The ToDictionary
call just expressly performs this mapping