I think those with even a slight grasp on basic string manipulation, loops and dictionaries can work out how to populate a Dictionary from a String such as this:
Black:#00000|Green:#008000| (where “Black” is the Key and “#000000” is the Value)
But what is the most ‘elegant’ way of doing it in your opinion? What is the most efficient/more concise coding I can use to achieve it? So far I have:
public static Dictionary<String, String> ThemeColors
{
get
{
Dictionary<String, String> themeColors = new Dictionary<string, string>();
foreach (String colorAndCode in GetSettingByName("ThemeColors").ToString().Split('|'))
{
themeColors.Add(colorAndCode.Split(':').First(), colorAndCode.Split(':').Last());
}
return themeColors;
}
}
GetSettingByName(“ThemeColours”) returns the string above (in Bold).
It’s functional obviously, it all works, but I want to make sure I’m beginning to think beyond this now and working out the best way of doing things rather than just getting it working.
Can I use a yield on the Dictionary loop for example??
I actually like a slight variant of your approach best:
The only difference is that the second
Split()is done only once, and direct indexing is rather thanFirst()andLast().Now
ToDictionary()is great when it makes sense to include something in a wider query, and I certainly wouldn’t consider it wrong, but it’s not like your approach is particularly verbose or anything.But I like that it’s easy to change your approach to tolerate duplicates (use
dict[parts[0]] = parts[1]and it’ll over-write duplicates rather than throwing), but it’s also easy to change to throw forBlack:#00000:#010101by testing the size ofparts.In the other direction, if you’ve a need to get as quick a parsing of a massive string as possible, then throw elegance out the window and replace it with something that scans throught the string tokenising by
|rather than usingSplit().Meanwhile, the above fits a nice middle-ground between concision and precision.