从分隔字符串填充Dictionary <String,String>的最"优雅"方式

4 c# string dictionary split

我认为那些对基本字符串操作,循环和字典有轻微把握的人可以解决如何从字符串填充字典,如下所示:

黑色:#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吗?

Har*_*san 8

 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)

  • 我已经完成了`.Select(x => x.Split(new [] {':'},2)).ToDictionary(x => x [0],x => x [1])` (5认同)
  • LINQ总是比foreach慢(Linq到对象使用For在场景后面)重构代码拆分只有一次才能实现.我认为有时人们过度使用LINQ只是因为很酷而不关心性能 (2认同)