Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if string value is in the Enum list?

Tags:

c#

c#-3.0

c#-4.0

In my query string, I have an age variable ?age=New_Born.

Is there a way I can check if this string value New_Born is in my Enum list

[Flags] public enum Age {     New_Born = 1,     Toddler = 2,     Preschool = 4,     Kindergarten = 8 } 

I could use if statement for right now, but if my Enum list gets bigger. I want to find a better way to do it. I am thinking about to use Linq, just not sure how to do it.

like image 671
qinking126 Avatar asked May 29 '12 17:05

qinking126


People also ask

How do you check if a string is present in enum?

toList()). contains(aString); EventNames is the name of the enum while getEvent() is what returns the associated string value of each enum member.

How do you check if a string is in an enum Python?

To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

How do you check if a string is in an enum C#?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false.


2 Answers

You can use:

 Enum.IsDefined(typeof(Age), youragevariable) 
like image 151
AaronS Avatar answered Oct 03 '22 10:10

AaronS


You can use the Enum.TryParse method:

Age age; if (Enum.TryParse<Age>("New_Born", out age)) {     // You now have the value in age  } 
like image 24
John Koerner Avatar answered Oct 03 '22 09:10

John Koerner