Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a more efficient / tidier way of breaking this string down?

I'm trying to break down this string into 2 colours and wondered if there is a neater way of achieving the same result?

// Obtain colour values
string cssConfig = "primary-colour:Red, secondary-colour:Blue";
var parts = cssConfig.Split(',');
var colour1 = parts[0].Split(':')[1];
var colour2 = parts[1].Split(':')[1];
like image 334
Andrew Avatar asked May 13 '11 08:05

Andrew


1 Answers

You could use regex

string cssConfig = "primary-colour:Red, secondary-colour:Blue";
var reg = new Regex(@"([\w\-]+)\:([\w\-]+)");
foreach (Match match in reg.Matches(cssConfig))
{

}

Also you could do something with LINQ

    var cssConfigDict = cssConfig.Split(',')
                        .Select(x => x.Split(':'))
                        .ToDictionary(x => x.FirstOrDefault(), y => y.LastOrDefault());

There is probably a better way with LINQ!

like image 150
David Avatar answered Oct 28 '22 16:10

David