我认为那些对基本字符串操作,循环和字典有轻微把握的人可以解决如何从字符串填充字典,如下所示:
黑色:#00000 |绿:#008000 | (其中"黑色"是键,"#000000"是值)
但是在你看来,最优雅的做法是什么?我可以使用哪种最有效/更简洁的编码来实现它?到目前为止,我有:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
GetSettingByName("ThemeColours")返回上面的字符串(以粗体显示).
它的功能显而易见,一切正常,但我想确保我现在开始思考这个问题并制定最好的做事方式而不仅仅是让它发挥作用.
我可以在Dictionary循环上使用yield吗?
public static Dictionary<String, String> ThemeColors
{
get
{
return GetSettingByName("ThemeColors").ToString().Split('|').ToDictionary(colorAndCode => colorAndCode.Split(':').First(), colorAndCode => colorAndCode.Split(':').Last());
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论中建议更优雅的方式
public static Dictionary<String, String> ThemeColors2
{
get
{
return GetSettingByName("ThemeColors").ToString().Split('|').Select(x => x.Split(new[] { ':' }, 2)).ToDictionary(x => x[0], x => x[1]);
}
}
Run Code Online (Sandbox Code Playgroud)