【问题标题】:IConfiguration.GetSection with Where selectorIConfiguration.GetSection 与 Where 选择器
【发布时间】:2020-11-12 07:53:40
【问题描述】:

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

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

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

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

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

但我总是陷入死胡同,任何建议都将不胜感激!

【问题讨论】:

  • 在设置文件中显示部分的外观。

标签: asp.net-core asp.net-mvc-5 asp.net-core-3.1 c#-8.0


【解决方案1】:

如果你想使用.Where,它需要是一个列表,这里有一个演示:

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"
    }
  ]

启动:

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

结果:

如果你没有得到list,又想使用.where,你可以尝试先把它改成list。这里有一个demo。 appsettings.json:

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

启动:

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

结果:

【讨论】:

  • 啊哈! Get> 是缺少的链接,我知道它必须是一个可枚举的列表,但我就是不知道如何到达那里,现在很明显。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2013-03-01
相关资源
最近更新 更多