开发者

Is there a better way to store a list of strings in an applications config file than using a StringCollection?

开发者 https://www.devze.com 2022-12-19 23:23 出处:网络
I have a list of filenames I need to store in my applications config file. The only collection that comes up in the initial combo box on the settings page is System.Collections.Specialized.StringColl

I have a list of filenames I need to store in my applications config file.

The only collection that comes up in the initial combo box on the settings page is System.Collections.Specialized.StringCollection. Now initially I didn't query this as I converted this to a List<string> straight away. There was one piece of code I wasn't happy with which was the copying of this list to and from the ListBox on the configuration dialog:

public List<string> ImageNames
{
    get
    {
        return folderImages.Items.ToList();
    }
    set
    {
        folderImages.Items.AddRange(value.ToArray());
    }
}

However, I've been revisiting my code and thought that if I kept the list as a StringCollection I could improve this code. Everywhere else I used the list/collection was OK, but this conversion still isn't to my liking:

public String开发者_JAVA技巧Collection ImageNames
{
    get
    {
        var names = new StringCollection();
        names.AddRange(folderImages.Items.ToList().ToArray());
        return names;
    }
    set
    {
        value.ToList().ForEach(imageName => folderImages.Items.Add(imageName));
    }
}

Actually, now I see the code side-by-side (as it were) I'm thinking that the List<string> version is "cleaner" - it's certainly clearer.

So is there another collection or list type I can store in the settings file? I'd really like to avoid the conversion on reading and writing the settings file if at all possible.

Failing that - is there a cleaner way of converting between a StringCollection and an ListBox.ObjectCollection (the ListBox.Items)?


You can store a System.Object into the app's settings, its not in the initial combo box, but it is there, then you can just store your data directly to and from the object.


In the end I actually reverted to my original code, but with much cleaner conversions between the StringCollection and List<string> - the ugliness of which was my starting point.

So now on start up I have:

possibleImageNames = Properties.Settings.Default.Images.ToList();

and on shut down (where I update the config file) I have:

Properties.Settings.Default.Images.Clear();
Properties.Settings.Default.Images.AddRange(possibleImageNames.ToArray());

Where the ToList method on the StringCollection is an extension method - used to encapsulate the looping code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号