Search code examples
asp.net-coreasp.net-mvc-5asp.net-core-3.1c#-8.0

IConfiguration.GetSection with Where selector


I'm using IConfiguration.GetSection to retrieve configuration information from a config file:

var loggingProviders = Config.GetSection( "Logging" ).Get<LoggingProviders>();

which works just fine, but I want to only retrieve entries that are enabled, so I want to do either of these:

var loggingProviders = Config.GetSection( "Logging" ).Get<LoggingProviders>().Where( x => x.Enabled == true );

var loggingProviders = Config.GetSection( "Logging" ).Where( x => x.Enabled == true ).Get<LoggingProviders>();

But I keep getting hitting a dead end, any advice would be appreciated!


Solution

  • If you want to use .Where,it needs to be a list,here is a demo:

    public class LoggingProviders
        {
            public int Id { get; set; }
            public bool Enabled { get; set; }
        }
    

    appsettings.json:

    "Logging1": [
        {
          "Id": "1",
          "Enabled": "true"
        },
        {
          "Id": "2",
          "Enabled": "true"
        },
        {
          "Id": "3",
          "Enabled": "false"
        }
      ]
    

    startup:

    public IConfiguration Configuration { get; }
    ...
    List<LoggingProviders> loggingProviders = Configuration.GetSection("Logging1").Get<List<LoggingProviders>>().Where(x => x.Enabled == true).ToList();
    

    result: enter image description here

    If you don't get a list,and want to use .where,you can try to change it to list first.Here is a demo. appsettings.json:

    "Logging1": 
        {
          "Id": "1",
          "Enabled": "true"
        },
    

    startup:

    public IConfiguration Configuration { get; }
        ...
    List<LoggingProviders> l= new List<LoggingProviders>();
    l.Add(Configuration.GetSection("Logging1").Get<LoggingProviders>());
    List<LoggingProviders> loggingProviders = l.Where(x => x.Enabled == true).ToList();
    

    result: enter image description here