简体   繁体   中英

AppSettings find key by value

I have a hopefully a very simple question.

I want to find a certain key from AppSettings in Web.config if i have the value

So to keep it simple is there a possibility to find AppSettings entry by specifying the value instead of the key

<appSettings>
  <add key="my:Hello" value="world"/>
  <add key="my:Test" value="New"/>
  <add key="my:Test2" value="SecondThing"/>
  etc...
</appSettings>

lets say i have somewhere inside my code world and i want to find the appsetting's key Hello . Is there a possibility to do so?

I do not want to get questions on why i want to do this or answers like just save this inside some DB.

you could do something like this:

var matches = ConfigurationManager.AppSettings.AllKeys.Select(t => 
new { Key = t, Value = 
ConfigurationManager.AppSettings[t] }).Where(i => i.Value == "world");

(Obviously this returns a key/value pair, you could add .Select(k => k.Key); to just get the key. Also note, using where will return multiples potentially, you could use SingleOrDefault/FirstOrDefault as an alternative)

You could retrieve all keys and find the one that contains the value:

foreach (string key in ConfigurationManager.AppSettings)
{
    if (ConfigurationManager.AppSettings[key] == "world") 
    {
        return key;
    }
}
var settings = ConfigurationManager.AppSettings;
var keys = settings.AllKeys.Where(k => settings[k] == "world");

but note - values are not unique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM