简体   繁体   中英

Enum array Contains String Dictionary Key C#

I am using a Dictionary with key, value as of type string

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

There is a custom enum class like this exists

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

There is a permitted list of values from this enum available

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

How can we check the dictionary contains atleast one key from the array permitted_list, with a not null value

I used this code to check atleast one not null value exists in the dictionary

        //CHECK  atleast one not null value exists                     
        bool canProceed=dictionary.Any(e => !string.IsNullOrWhiteSpace(e.Value));                

Can we extend this to check for the existence of dictionary Key from the list of enums

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

Instead of using new Dictionary<string, string>(), try to use new Dictionary<AnimalName, string>()

it will simplify the process and make you sure there is no error or mis-spelling

I have this little mess for you:

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

Let us work backwards. This is the check that the value is not null or whitespace that you already had:

!string.IsNullOrWhiteSpace(e.Value)

Here we are checking if permitted_list contains the animalName :

permitted_list.Contains(animalName)

However, animalName must be of type AnimalName , to get it we are going to use Enum.TryParse :

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

However, that would not work, because you have "cat", but we need "Cat". So let us use the overload ( That I somehow missed the first time I wrote this ):

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()));

You can also do it in this way:

        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;
        });

In this code, first of all, we are trying to parse Keys of the dictionary to the enum. If it can successfully be parsed, it means there's an enum in the key string. The next step will be checking if that enum is permitted. If it's permitted, the if condition will return true.

** Update: True in TryParse method is for case ignoring. So, it won't be case-sensitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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