Store Dictionary in application settings

后端 未结 9 1615
感动是毒
感动是毒 2020-11-30 08:28

I have a dictionary of strings that i want the user to be able to add/remove info from then store it for them so it they can access it the next time the program restarts

9条回答
  •  攒了一身酷
    2020-11-30 08:55

    You can store a StringCollection. It is similar to this solution.

    I made 2 extension methods to convert between StringCollection and a Dictionary. This is the easiest way I could think of.

    public static class Extender
    {
        public static Dictionary ToDictionary(this StringCollection sc)
        {
            if (sc.Count % 2 != 0) throw new InvalidDataException("Broken dictionary");
    
            var dic = new Dictionary();
            for (var i = 0; i < sc.Count; i += 2)
            {
                dic.Add(sc[i], sc[i + 1]);
            }
            return dic;
        }
    
        public static StringCollection ToStringCollection(this Dictionary dic)
        {
            var sc = new StringCollection();
            foreach (var d in dic)
            {
                sc.Add(d.Key);
                sc.Add(d.Value);
            }
            return sc;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            //var sc = new StringCollection();
            //sc.Add("Key01");
            //sc.Add("Val01");
            //sc.Add("Key02");
            //sc.Add("Val02");
    
            var sc = Settings.Default.SC;
    
            var dic = sc.ToDictionary();
            var sc2 = dic.ToStringCollection();
    
            Settings.Default.SC = sc2;
            Settings.Default.Save();
        }
    }
    

提交回复
热议问题