So I have a string like:
"some key:some value; john:doe;age:234"
I already wrote a method that takes this string and returns a:
Dictionary<string,string>
Was curious if someone could do this via linq?
Assuming that delimiters cannot appear in keys or values:
var dict = str.Split(';')
.Select(s => s.Split(':'))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim()));
This is not the fastest way to do it, but it is the simplest.
You could also use a regex:
static readonly Regex parser = new Regex(@"([^:]):([^;])");
var dict = parser.GetMatches(str)
.Cast<Match>()
.ToDictionary(m => m.Groups[0].Value.Trim(),
m => m.Groups[0].Value.Trim()
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With