Search code examples
c#web-configapp-configconfigurationmanagerappsettings

Will I always get the keys in the same order when I call ConfigurationManager.AppSettings.AllKeys


For web.config and app.config, when I call ConfigurationManager.AppSettings.AllKeys, do I get the keys in the same order they appear in the config file all the time?

I couldn't find any mention of that on MSDN.


Solution

  • ConfigurationManager.AppSettings is of type NameValueCollection and their order is undetermined. AllKeys returns string array based on the NameValueCollection, thus its order will also be undetermined.

    See: NameValueCollection

    Collections of this type do not preserve the ordering of element, and no particular ordering is guaranteed when enumerating the collection.

    If you want a definite order the use

    ConfigurationManager.AppSettings.AllKeys.OrderBy(r=> r)