繁体   English   中英

枚举数组包含字符串字典键 C#

[英]Enum array Contains String Dictionary Key C#

我正在使用带有键、值作为字符串类型的字典

       var dictionary = new Dictionary<string, string>();
        dictionary.Add("cat",null);
        dictionary.Add("dog", "vals");
        dictionary.Add("Tiger", "s");   

有一个像这样的自定义枚举 class 存在

public enum AnimalName
{      
    Cat = 0,         
    Dog = 1,       
    Rabit = 2,      
    Tiger = 3,        
    Lion = 4
}
 

此枚举中有一个允许的值列表可用

        AnimalName[] permitted_list   = {
                AnimalName.Cat,
                AnimalName.Dog,
                AnimalName.Rabit
            };
        

我们如何检查字典是否包含数组 allowed_list 中的至少一个键,而不是 null 值

我用这段代码检查了字典中至少有一个不是 null 值

        //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"); 

不要使用 new Dictionary<string, string>(),而是尝试使用 new Dictionary<AnimalName, string>()

它将简化流程并确保您没有错误或拼写错误

我有这个小麻烦给你:

bool canProceed = dictionary.Any(
    e =>
        Enum.TryParse<AnimalName>(e.Key, ignoreCase: true, out var animalName)
        && permitted_list.Contains(animalName)
        && !string.IsNullOrWhiteSpace(e.Value)
);

让我们向后工作。 这是检查该值不是 null 或您已经拥有的空格:

!string.IsNullOrWhiteSpace(e.Value)

在这里,我们正在检查animalName permitted_list

permitted_list.Contains(animalName)

但是, animalName必须是AnimalName类型,要获得它,我们将使用Enum.TryParse

Enum.TryParse<AnimalName>(e.Key, out var animalName)

然而,这行不通,因为你有“猫”,但我们需要“猫”。 所以让我们使用重载(我第一次写这个时不知何故错过了):

Enum.TryParse<AnimalName>(e.Key, ignoreCase: true, out var animalName)
bool canProceed=dictionary.Any(e => !string.IsNullOrWhiteSpace(e.Value) && permitted_list.Any(p => p.ToString().ToLower() == e.Key.ToLower()));

你也可以这样做:

        AnimalName animalName = new AnimalName();
        bool canProceed = dictionary.Any(dic => {
            if (Enum.TryParse(dic.Key, true, out animalName) == true)
            {
                return permitted_list.Any(permittedAnimal => permittedAnimal ==
            animalName);
            }
            else return false;
        });

在这段代码中,首先,我们试图将字典的键解析为枚举。 如果可以成功解析,则说明密钥字符串中有一个枚举。 下一步将检查是否允许该枚举。 如果允许,则 if 条件将返回 true。

** 更新:TryParse 方法中的 True 用于忽略大小写。 因此,它不会区分大小写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM