开发者

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,
 开发者_如何学Go   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.


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.


Use Enum.IsDefined

example:

public enum enStage {Work, Payment, Record, Return, Reject};
int StageValue = 4;

Enum.IsDefined(typeof(enStage), StageValue)


You can do this in .NET 4.0+ using Enum.HasFlag(Enum) method,

UserStatus status = UserStatus.Unverified; // just assumed status is Unverified

bool ok = (UserStatus.Unverified | UserStatus.Active).HasFlag(status);

You can also do the same by assigning into a variable like,

UserStatus status = UserStatus.Active; // just assumed status is Active

UserStatus unverifiedOrActive = UserStatus.Unverified | UserStatus.Active;

bool ok = unverifiedOrActive.HasFlag(status);


UserStatus userStatus = null;
Eum.TryParse<UserStatus>(status.ToString(), out userStatus);

if(userStatus != null)
{
  //it is not in the list
}


Why not create a method to encapsulate it?

public bool UnVerifiedOrActive(User user)
{
    return (user.UserStatus == UserStatus.Unverified || 
            user.UserStatus == UserStatus.Active);
}


You can try following

UserStatus ustatus;
if(Enum.TryParse<UserStatus>(c.ToString(), out ustatus))
{
 ..Your logic
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜