user1464139
user1464139

Reputation:

How can I check an array of strings against an Enum and return the highest value that's found?

I have the following code where the variable userRoles is a string array that can contain and or all of "Super", "Admin", "User" or "Guest".

    public static RoleType GetMaxRole()
    {
        var userRoles = Roles.GetRolesForUser();
        // var maxRole = userRoles.Max();
        if userRoles.Contains("Super")
            return RoleType.Super;
        if userRoles.Contains("Admin")
            return RoleType.Admin;
        if userRoles.Contains("User")
            return RoleType.User;
        if userRoles.Contains("Guest")
            return RoleType.Guest;
        return RoleType.Default;
    }

Here is the enum I am using:

public enum RoleType
{
    Default = 10,
    Guest = 20,
    User = 30,
    Admin = 40,
    Super = 50
}

Is there a way that I could achieve the same without multiple if statements. Some way I could have the userRoles array checked against the Enum?

Upvotes: 0

Views: 281

Answers (1)

Manuel Schweigert
Manuel Schweigert

Reputation: 4974

public static RoleType GetMaxRole()
{
    var userRoles = Roles.GetRolesForUser();
    var maxRole = userRoles.Max(x => (RoleType)Enum.Parse(typeof(RoleType), x));
    return maxRole;
}

Upvotes: 2

Related Questions