【发布时间】:2021-04-07 09:56:24
【问题描述】:
我正在使用带有 key 、 value 的字符串类型的字典
var dictionary = new Dictionary<string, string>();
dictionary.Add("cat",null);
dictionary.Add("dog", "vals");
dictionary.Add("Tiger", "s");
存在这样的自定义枚举类
public enum AnimalName
{
Cat = 0,
Dog = 1,
Rabit = 2,
Tiger = 3,
Lion = 4
}
此枚举中有一个可用的值列表
AnimalName[] permitted_list = {
AnimalName.Cat,
AnimalName.Dog,
AnimalName.Rabit
};
我们如何检查字典是否包含数组 allowed_list 中的至少一个键,且值不为空
我使用此代码检查字典中至少存在一个非空值
//CHECK atleast one not null value exists
bool canProceed=dictionary.Any(e => !string.IsNullOrWhiteSpace(e.Value));
我们可以扩展它以检查枚举列表中字典键是否存在
//Example in this case key Dog exists with a not null value So canProceed is TRUE
//in this case#2 canProceed is FALSE , since the only permitted_list key is Cat and its value is NULL
var dictionaryf = new Dictionary<string, string>();
dictionaryf.Add("cat",null);
dictionaryf.Add("Tiger", "s");
dictionaryf.Add("Lion", "exit sjs");
【问题讨论】:
-
当字典针对您所在位置的关键字搜索进行了优化时,我将遍历允许的列表,例如:
permitted_list .Select(x => $"{x}".ToLower()) .Any(x => dictionary.TryGetValue(x, out string value) && value != null);
标签: c# dictionary enums