簡體   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