Search code examples
c#configurationmanager

Get ConfigurationManager.AppSettings Key name along with values


string[] Accounts = ConfigurationManager.AppSettings.AllKeys
                        .Where(key => key.StartsWith("Account"))
                        .Select(key => ConfigurationManager.AppSettings[key])
                        .ToArray();

Here I'm getting all the AppSettings that starts with Account but currently they only return the value of the object.

Is there a way I can turn string[] Accounts into List<Tuple<String, String>> Accounts so it would be like List<Tuple<key, value>> Accounts


Solution

  • Absolutely - all you need to do is changing your Select to return the desired tuple, and calling ToList in place of ToArray:

    List<Tuple<String,String>> Accounts = ConfigurationManager.AppSettings.AllKeys
        .Where(key => key.StartsWith("Account"))
        .Select(key => Tuple.Create(key, ConfigurationManager.AppSettings[key]))
        .ToList();