How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
There are two ways to iterate an Enum
:
1. var values = Enum.GetValues(typeof(myenum))
2. var values = Enum.GetNames(typeof(myenum))
The first will give you values in form on an array of **object
**s, and the second will give you values in form of an array of **String
**s.
Use it in a foreach
loop as below:
foreach(var value in values)
{
// Do operations here
}
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}
(The current accepted answer has a cast that I don't think is needed (although I may be wrong).)
If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:
public static T[] GetEnumValues<T>() where T : struct, IComparable, IFormattable, IConvertible
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException(string.Format("{0} is not of type System.Enum", typeof(T)));
}
return Enum.GetValues(typeof(T)) as T[];
}
And you can use it like below:
static readonly YourEnum[] _values = GetEnumValues<YourEnum>();
Of course you can return IEnumerable<T>
, but that buys you nothing here.
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());
}
}
This question appears in Chapter 10 of "C# Step by Step 2013"
The author uses a double for-loop to iterate through a pair of Enumerators (to create a full deck of cards):
class Pack
{
public const int NumSuits = 4;
public const int CardsPerSuit = 13;
private PlayingCard[,] cardPack;
public Pack()
{
this.cardPack = new PlayingCard[NumSuits, CardsPerSuit];
for (Suit suit = Suit.Clubs; suit <= Suit.Spades; suit++)
{
for (Value value = Value.Two; value <= Value.Ace; value++)
{
cardPack[(int)suit, (int)value] = new PlayingCard(suit, value);
}
}
}
}
In this case, Suit
and Value
are both enumerations:
enum Suit { Clubs, Diamonds, Hearts, Spades }
enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}
and PlayingCard
is a card object with a defined Suit
and Value
:
class PlayingCard
{
private readonly Suit suit;
private readonly Value value;
public PlayingCard(Suit s, Value v)
{
this.suit = s;
this.value = v;
}
}
I know it is a bit messy, but if you are fan of one-liners, here is one:
((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));