Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value is in enum list

I have a fairly basic question: How can I check if a given value is contained in a list of enum values?

For example, I have this enum:

public enum UserStatus {     Unverified,     Active,     Removed,     Suspended,     Banned } 

Now I want to check if status in (Unverified, Active)

I know this works:

bool ok = status == UserStatus.Unverified || status == UserStatus.Active; 

But there has to be a more elegant way to write this.

The topic of this question is very similar, but that's dealing with flags enums, and this is not a flags enum.

like image 521
Jerad Rose Avatar asked Mar 16 '11 03:03

Jerad Rose


People also ask

Is value in 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.

Can enum be a list?

Yes. If you do not care about the order, use EnumSet , an implementation of Set . enum Animal{ DOG , CAT , BIRD , BAT ; } Set<Animal> flyingAnimals = EnumSet.


2 Answers

Here is an extension method that helps a lot in a lot of circumstances.

public static class Ext {     public static bool In<T>(this T val, params T[] values) where T : struct     {         return values.Contains(val);     } } 

Usage:

Console.WriteLine(1.In(2, 1, 3)); Console.WriteLine(1.In(2, 3)); Console.WriteLine(UserStatus.Active.In(UserStatus.Removed, UserStatus.Banned)); 
like image 57
Cheng Chen Avatar answered Sep 29 '22 01:09

Cheng Chen


If it is a longer list of enums, you can use:

var allowed = new List<UserStatus> { UserStatus.Unverified, UserStatus.Active }; bool ok = allowed.Contains(status); 

Otherwise there is no way around the long || predicate, checking for each allowed value.

like image 37
Femaref Avatar answered Sep 29 '22 00:09

Femaref