Most efficient way to parse a flagged enum to a list

前端 未结 6 1289
猫巷女王i
猫巷女王i 2021-01-01 09:06

I have a flagged enum and need to retrieve the names of all values set on it.

I am currently taking advantage of the enum\'s ToString() method which returns the eleme

6条回答
  •  生来不讨喜
    2021-01-01 09:30

    List GetRoleNames(Roles roles) =>
        Enum.GetValues(typeof(Roles))
            .Cast()
            .Where(role => roles.HasFlag(role))
            .Select(role => role.ToString())
            .ToList();
    
    void TestRoleSelection()
    {
        var selectedRoles = (Roles)6;
        var roleNames = GetRoleNames(selectedRoles);
        Console.WriteLine(string.Join(",", roleNames));
        // Output: Admin,User
    }
    
    [Flags]
    enum Roles
    {
        SuperAdmin = 1,
        Admin = 2,
        User = 4,
        Anonymous = 8
    }
    

提交回复
热议问题