c# - How to enumerate an enum

ID : 91

viewed : 486

Tags : c#.netloopsenumsenumerationc#





Top 5 Answer for c# - How to enumerate an enum

vote vote

92

foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { } 

Note: The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster.

vote vote

84

It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.

public enum Suits {     Spades,     Hearts,     Clubs,     Diamonds,     NumSuits }  public void PrintAllSuits() {     foreach (string name in Enum.GetNames(typeof(Suits)))     {         System.Console.WriteLine(name);     } } 

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

public enum Suits {     Spades,     Hearts,     Clubs,     Diamonds,     NumSuits }  public void PrintAllSuits() {     foreach (var suit in Enum.GetValues(typeof(Suits)))     {         System.Console.WriteLine(suit.ToString());     } } 
vote vote

77

I made some extensions for easy enum usage. Maybe someone can use it...

public static class EnumExtensions {     /// <summary>     /// Gets all items for an enum value.     /// </summary>     /// <typeparam name="T"></typeparam>     /// <param name="value">The value.</param>     /// <returns></returns>     public static IEnumerable<T> GetAllItems<T>(this Enum value)     {         foreach (object item in Enum.GetValues(typeof(T)))         {             yield return (T)item;         }     }      /// <summary>     /// Gets all items for an enum type.     /// </summary>     /// <typeparam name="T"></typeparam>     /// <param name="value">The value.</param>     /// <returns></returns>     public static IEnumerable<T> GetAllItems<T>() where T : struct     {         foreach (object item in Enum.GetValues(typeof(T)))         {             yield return (T)item;         }     }      /// <summary>     /// Gets all combined items from an enum value.     /// </summary>     /// <typeparam name="T"></typeparam>     /// <param name="value">The value.</param>     /// <returns></returns>     /// <example>     /// Displays ValueA and ValueB.     /// <code>     /// EnumExample dummy = EnumExample.Combi;     /// foreach (var item in dummy.GetAllSelectedItems<EnumExample>())     /// {     ///    Console.WriteLine(item);     /// }     /// </code>     /// </example>     public static IEnumerable<T> GetAllSelectedItems<T>(this Enum value)     {         int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);          foreach (object item in Enum.GetValues(typeof(T)))         {             int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);              if (itemAsInt == (valueAsInt & itemAsInt))             {                 yield return (T)item;             }         }     }      /// <summary>     /// Determines whether the enum value contains a specific value.     /// </summary>     /// <param name="value">The value.</param>     /// <param name="request">The request.</param>     /// <returns>     ///     <c>true</c> if value contains the specified value; otherwise, <c>false</c>.     /// </returns>     /// <example>     /// <code>     /// EnumExample dummy = EnumExample.Combi;     /// if (dummy.Contains<EnumExample>(EnumExample.ValueA))     /// {     ///     Console.WriteLine("dummy contains EnumExample.ValueA");     /// }     /// </code>     /// </example>     public static bool Contains<T>(this Enum value, T request)     {         int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);         int requestAsInt = Convert.ToInt32(request, CultureInfo.InvariantCulture);          if (requestAsInt == (valueAsInt & requestAsInt))         {             return true;         }          return false;     } } 

The enum itself must be decorated with the FlagsAttribute:

[Flags] public enum EnumExample {     ValueA = 1,     ValueB = 2,     ValueC = 4,     ValueD = 8,     Combi = ValueA | ValueB } 
vote vote

66

Some versions of the .NET framework do not support Enum.GetValues. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:

public Enum[] GetValues(Enum enumeration) {     FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);     Enum[] enumerations = new Enum[fields.Length];      for (var i = 0; i < fields.Length; i++)         enumerations[i] = (Enum) fields[i].GetValue(enumeration);      return enumerations; } 

As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.

vote vote

57

Use Cast<T>:

var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>(); 

There you go, IEnumerable<Suit>.

Top 3 video Explaining c# - How to enumerate an enum







Related QUESTION?