我有这个验证,它在字典中检查键和值是否有效但必须修改它以接受空键字典并在检查内部键和值时将其视为空集合
将逻辑更改为接受值为Dictionary
的nullList<KeyValuePair<string, Dictionary<string, string>>> properties = new List<KeyValuePair<string, Dictionary<string, string>>>();
properties.Add(new KeyValuePair<string, Dictionary<string, string>>("test", null));
var list = properties.Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(value => string.IsNullOrWhiteSpace(value))));
当我传递null时失败。请让我知道我需要在select语句中更改以将null视为空内部字典
答案 0 :(得分:2)
因为您想将空值Dictionary视为空,而空字典没有键或值,您应该忽略空值:
var list = properties.Where(p => p.Value != null)
.Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key)
|| cat.Value.Values.Any(value => string.IsNullOrWhiteSpace(value))));
答案 1 :(得分:1)
在访问此属性之前,您需要检查cat.Value
null
:
var properties = new List<KeyValuePair<string, Dictionary<string, string>>>
{
new KeyValuePair<string, Dictionary<string, string>>("test", null)
};
var list = properties.Select(cat => cat.Value != null && (cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(string.IsNullOrWhiteSpace))));
或者你可以这样做:
var list = properties
.Select(kvp=> new KeyValuePair<string, Dictionary<string,string>>(kvp.Key, kvp.Value ?? new Dictionary<string, string>()))
.Select(cat => cat.Value.Keys.Any(key => string.IsNullOrWhiteSpace(key) || cat.Value.Values.Any(string.IsNullOrWhiteSpace)));