【问题标题】:Find if Key that has a null value exists in IConfiguration查找 IConfiguration 中是否存在具有空值的 Key
【发布时间】:2020-08-30 03:40:20
【问题描述】:

我有:

IConfiguration cfg;
string key;

当密钥具有 'null' 值时,我必须检测 key 是否存在于 cfg 中。

我知道钥匙在里面,我用调试器看到它​​,但我需要一种方法来检测它。

我认为cfg.GetSection(key).Exists() 会返回 True。
但它总是返回 False

根据文档,cfg.GetSection(key)从不返回 null,即使 key 不存在,所以它没有帮助。

【问题讨论】:

标签: c# .net .net-core configuration


【解决方案1】:

使用cfg.AsEnumerable() 获取配置中的密钥。
您可以登录并查看它们:

foreach (var kv in cfg.AsEnumerable()) 
{
    Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}

=> 所以您需要做的就是找出您要查找的特定键是否在此 IEnumerable 中。

var keyNames = cfg.AsEnumerable().ToDictionary(x => x.Key, x => x.Value);

if (keyNames.ContainsKey(keyName))
{
    keyExistsInConfiguration = true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2019-06-18
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多