c# Get all enum values greater than a given value?
I have the following enumeration of membership roles:
public enum RoleName
{
RegisteredUser,
Moderator,
Administrator,
Owner
}
I want to be able to fetch all roles greater than or equal to a given role.
For instance I input Administrator and I get an IEnumerable with RoleName.Administration
and RoleName.Owner
Something of this sort:
public static void AddUserToRole(string username, RoleName level)
{
var roles = Enum.GetValues(typeof(RoleName)).Cast<R>().ToList().Where(role => level > role);
foreach (var role in roles)
{
Roles.AddUserToRole(username, role);
}
}
You can use the following helper method to give you a set of roles allowed for a given role:
private IEnumerable<RoleName> AllAllowedRoles(RoleName level)
{
return Enum.GetValues(typeof(RoleName)).Cast<RoleName>().Where(role => level >= role);
}
And then assign all of them to the user.
Probably depending on version of .NET. But this works very well for me:
There is no need to convert or to use special tricks. Just compare with the usual operators:
enum Test { a1, a2, a3, a4 }
class Program
{
static void Main(string[] args)
{
Test a = Test.a2;
Console.WriteLine((a > Test.a1));
Console.WriteLine((a > Test.a2));
Console.WriteLine((a > Test.a3));
Console.WriteLine((a > Test.a4));
Console.ReadKey();
}
}
in order to have a better definition of which role is greater than the other you need to assign numeric values to your roles like this:
public enum RoleName
{
RegisteredUser = 2,
Moderator = 4,
Administrator = 8,
Owner = 16
}
Now if you cast any instance of type RoleName to (int) you will get the numeric value and therefore you will be able to compare them against each other.
Note:
1. Here I use powers of 2 as values to allow combining RoleNames using bit-wise operators.
上一篇: 用空格在ComboBox中显示枚举
下一篇: c#获取大于给定值的所有枚举值?