IConfiguration.GetSection与Where选择器

问题描述

我正在使用IConfiguration.GetSection配置文件中检索配置信息:

function Number() { [native code] }100507580901124105

这很好用,但是我只想检索已启用的条目,所以我要执行以下任一操作:

totAmt

但是我一直死胡同,任何建议都将不胜感激!

解决方法

如果要使用.Where,它需要一个列表,下面是一个演示:

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

appsettings.json:

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

启动:

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

结果: enter image description here

如果您没有列表,并且想使用.where,可以尝试将其更改为第一个列表。这里是一个演示。 appsettings.json:

"Logging1": 
    {
      "Id": "1",

启动:

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();

结果: enter image description here