Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an enum has a field that equals a string

Tags:

c#

enums

I have an enum

public enum FileExtentions {
    mp3,
    mpeg
}

And I have a FileInfo of which I want to check if the extension is in the previous enum. I was hoping I could do a

FileExtensions.Any(e=>e.ToString().Equals(file.Extension));

But that would have been too awesome. Any ideas?

like image 824
Boris Callens Avatar asked Nov 29 '08 21:11

Boris Callens


People also ask

How do you check if a string is equal to an enum?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.

Can == be used on enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.


2 Answers

What's the reason behind AnyEquals? Did you overlook Contains?

bool result = Enum.GetNames(typeof(FileExtensions)).Contains("mp3");
like image 102
Konrad Rudolph Avatar answered Sep 21 '22 22:09

Konrad Rudolph


While pressing submit I thought of the answer myself:

Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension))
like image 29
Boris Callens Avatar answered Sep 19 '22 22:09

Boris Callens