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.
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.
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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With