Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary<string,string> from a semicolon separated string using linq

Tags:

c#

linq

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?

like image 551
codecompleting Avatar asked Feb 22 '26 10:02

codecompleting


1 Answers

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()
                 );
like image 198
SLaks Avatar answered Feb 23 '26 23:02

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!