C# AppSettings array

1.3k Views Asked by At

I have some string constants that I need to access from multiple files. Since the values of these constants might change from time to time, I decided to put them in AppSettings rather than a constants class so that I don't have to recompile every time I change a constant.

Sometimes I need to work with the individual strings and sometimes I need to work with all of them at once. I'd like to do something like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="CONST1" value="Hi, I'm the first constant." />
        <add key="CONST2" value="I'm the second." />
        <add key="CONST3" value="And I'm the third." />

        <add key="CONST_ARR" value=[CONST1, CONST2, CONST3] />
    </appSettings>
</configuration>

The reasoning being that I'll then be able to do stuff like

public Dictionary<string, List<double>> GetData(){
    var ret = new Dictionary<string, List<double>>();
    foreach(string key in ConfigurationManager.AppSettings["CONST_ARR"])
        ret.Add(key, foo(key));
    return ret;
}

//...

Dictionary<string, List<double>> dataset = GetData();

public void ProcessData1(){
    List<double> data = dataset[ConfigurationManager.AppSettings["CONST1"]];
    //...
}

Is there a way to do this? I'm pretty new to this and I concede that this might be horrendous design.

1

There are 1 best solutions below

1
On BEST ANSWER

You do not need to put array of key in AppSettings key as you can iterate all keys of AppSetting from code itself. So, your AppSettings should be like this :

 <appSettings>
    <add key="CONST1" value="Hi, I'm the first constant." />
    <add key="CONST2" value="I'm the second." />
    <add key="CONST3" value="And I'm the third." />
</appSettings>

After this, you can create global static dictionary which you can access from all part of the program :

public static Dictionary<string, List<double>> Dataset
{
       get
       {
            var ret = new Dictionary<string, List<double>>();
            // Iterate through each key of AppSettings
            foreach (string key in ConfigurationManager.AppSettings.AllKeys)
                ret.Add(key, Foo(ConfigurationManager.AppSettings[key]));
            eturn ret;
        }
}

As Foo method has been accessed from static property, you need to define Foo method as static method. so, your Foo method should look like this :

private static List<double> Foo(string key)
{
    // Process and return value 
    return Enumerable.Empty<double>().ToList(); // returning empty collection for demo
}

Now, you can access Dataset dictionary by its key in following way :

public void ProcessData1()
{
    List<double> data = Dataset["CONST1"];
    //...
}