Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over enum?

Tags:

I'm trying to iterate over an enum, and call a method using each of its values as a parameter. There has to be a better way to do it than what I have now:

foreach (string gameObjectType in Enum.GetNames(typeof(GameObjectType))) {      GameObjectType kind = (GameObjectType) Enum.Parse(typeof (GameObjectType), gameObjectType);      IDictionary<string, string> gameObjectData = PersistentUtils.LoadGameObject(kind, persistentState); }  //...  public static IDictionary<string, string> LoadGameObject(GameObjectType gameObjectType, IPersistentState persistentState) { /* ... */ } 

Getting the enum names as strings, then parsing them back to enums, feels hideous.

like image 698
Nick Heiner Avatar asked Apr 13 '10 19:04

Nick Heiner


People also ask

Can I iterate through enum Java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. You can iterate the contents of an enumeration using for loop, using forEach loop and, using java.

Can you iterate over an enum C#?

Iterating over an enum in C# Enums are kind of like integers , but you can't rely on their values to always be sequential or ascending. To get all values of an enum, we can use the Enum. GetValues static method. The following C# code snippet loops through all values of an enum and prints them on the console.

Can you loop through an enum C ++?

C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.

Are enums iterable Python?

Use the enumeration[member_name] to access a member by its name and enumeration(member_value) to access a member by its value. Enumerations are iterable. Enumeration members are hashable.


1 Answers

Well, you can use Enum.GetValues:

foreach (GameObjectType type in Enum.GetValues(typeof(GameObjectType)) {     ... } 

It's not strongly typed though - and IIRC it's pretty slow. An alternative is to use my UnconstrainedMelody project:

// Note that type will be inferred as GameObjectType :) foreach (var type in Enums.GetValues<GameObjectType>()) {     ... } 

UnconstrainedMelody is nice if you're doing a lot of work with enums, but it might be overkill for a single usage...

like image 196
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet