0

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?

  • Check this post: http://stackoverflow.com/questions/105372/how-to-enumerate-an-enum –  Oct 15 '12 at 04:04
  • your GetMaxRole is always just going to return one RoleType, even if there are many roles? – gideon Oct 15 '12 at 04:08

1 Answers1

2
public static RoleType GetMaxRole()
{
    var userRoles = Roles.GetRolesForUser();
    var maxRole = userRoles.Max(x => (RoleType)Enum.Parse(typeof(RoleType), x));
    return maxRole;
}
Manuel Schweigert
  • 4,406
  • 3
  • 17
  • 32