1

I am reading specific AppSetting key/value pairs in Web.config, using hard-coded values, with the code below. This works.

string[] filteredList = webConfigApp.AppSettings.Settings.AllKeys.AsEnumerable().Where(x => x.Equals("appMode") || x.Equals("loggingMode") || x.Equals("ticketModeCache") || x.Equals("ticketMode")).ToArray();

Instead, I would like to read from a comma-separated list that is also in Web.config, for example:

<add key="setConfigValues" value="appMode,loggingMode,ticketModeCache,ticketMode,twilioMode,kioskId,kioskPrinterConfig" />

I know how to to parse and create a List<> doing something along these lines...

List<string> ConfigValues = ConfigurationManager.AppSettings["setConfigValues"].Split(',').ToList();

...but I am not sure how to code the Linq part to include values in the List.

How can I do this? I tried x.Contains but that does not work (understandably). I am looking to find AppSetting keys that are in the comma-delimited list. Thanks.

3 Answers 3

2

I would transform that into a case insensitive dictionary:

var configValues = ConfigurationManager.AppSettings["setConfigValues"]
    .Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
    .Distinct()
    .ToDictionary(
        item => item,
        item => webConfigApp.AppSettings.Settings[item].Value, 
        StringComparer.InvariantCultureIgnoreCase);


if (configValues.ContainsKey("loggingMode"))
{
    // do stuff
}

if (configValues.TryGetValue("loggingMode", out string value) && value == "on")
{
    // do stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

interesting. i was looking for just the key, then iterate for the values, but this gets the key and the value in the same array. nice!
1

Try using the Select() or Where() methods For example:

List<string> ConfigValues = ConfigurationManager.AppSettings["setConfigValues"].Split(',').ToList();
ConfigValues.Select(val => val == "x");

1 Comment

txs. your post got me thinking of other approaches.
0

The solution that worked was much easier than I thought. This worked for what I was trying to do:

string[] filteredList = ConfigurationManager.AppSettings["setConfigValues"].Split(',').ToArray();

Specifically, I am using the keys of the "setConfigValues" array to pull the Web.config values, so parsing the comma-delimited string into a string[] is enough.

        foreach (string s in filteredList) 
        {
            keyValues.Add(new KeyValuePair<string, string>(s, webConfigApp.AppSettings.Settings[s].Value));
        }

1 Comment

compare your code with the result of the code i proposed ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.