Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...