简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM