Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Get all enum values greater than a given value?

Tags:

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);     } } 
like image 305
bevacqua Avatar asked Jul 24 '11 15:07

bevacqua


1 Answers

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:

using System;  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();     } } 

Output:

True False False False 
like image 102
Bitterblue Avatar answered Oct 13 '22 00:10

Bitterblue