ConfigurationManager.AppSettings.AllKeys .Where( key => key.StartsWith( "Screen" ) ) .Select( key => ConfigurationManager.AppSettings[key] )
If you have a lot of settings (for example, 10K, as indicated in the comments), you can take advantage of the fact that the AppSettings collection is optimized for key search. To do this, you will have to try "Screen1", "Screen2", "Screen3", etc. several times. And stop when no value is found:
Enumerable.Range( 1, int.MaxValue ) .Select( i => ConfigurationManager.AppSettings[ "Screen" + i ] ) .TakeWhile( value => value != null )
This approach, however, is precisely the kind of “premature optimization” Mr. Knut warned us about. The configuration file simply does not have to contain many settings, period.
Another drawback: keep in mind that this approach assumes that there are no spaces in the numbering of the Screen settings. That is, if you have "Screen 1", "Screen 2" and "Screen 4", it will not record the latter. If you plan to have many of these parameters, it becomes very inconvenient to "change" all the numbers every time you add or remove settings.
source share