What is a more efficient / tidier way to crack this line?

I am trying to split this line into 2 colors and wonder if there is an easier way to achieve 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]; 
+6
source share
5 answers

You can use regex

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

You can also do something with LINQ

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

Most likely better with LINQ!

+7
source

Regex is definitely an opportunity, although whether it is β€œfaster” or more readable, depends on personal preferences and your ability to read regular expressions. If the actual use case for this really just reads these two colors, rather than an arbitrary number of colors, then I will probably just stay with the original solution. The goal is perfectly clear, keeping the code simple and avoiding subtle mistakes if Regexes are not your forte.

LINQ is probably the most readable option and easily reads a few key-value pairs, while still using a simple separation mechanism for data analysis.

From my experience, what you should definitely avoid for the sake of convenience is to write a very complex, general, and seemingly β€œneat” solution to the problem, it is small and simple.

+3
source

You can use LINQ methods:

 var colors = cssConfig.Split(',').Select(x => x.Split(':').Skip(1).Take(1)); 

Having said that, I stick to my method. This is clear code that everyone understands. The regex version and LINQ version are more obscure ...

+2
source

Check that it looks like your requirement to get the dictionary object from the string

Regex To Linq to Dictionary in C #

 string input = "abc:1|bbbb:2|xyz:45|p:120"; string pattern = @"(?<Key>[^:]+)(?:\:)(?<Value>[^|]+)(?:\|?)"; Dictionary<string, string> KVPs = ( from Match m in Regex.Matches( input, pattern ) select new { key = m.Groups["Key"].Value, value = m.Groups["Value"].Value } ).ToDictionary( p => p.key, p => p.value ); foreach ( KeyValuePair<string, string> kvp in KVPs ) Console.WriteLine( "{0,6} : {1,3}", kvp.Key, kvp.Value ); /* Outputs: abc : 1 bbbb : 2 xyz : 45 p : 120 */ 
+1
source

If you know that the order will always be the same. What do you need for your solution to work anyway, you could do:

 // Obtain colour values string cssConfig = "primary-colour:Red, secondary-colour:Blue"; var parts = cssConfig.Split(',',':'); var colour1 = parts[1]; var colour2 = parts[3]; 
0
source

Source: https://habr.com/ru/post/888010/


All Articles