Loop through C # enumeration keys and values

Given the C # enumeration:

public enum stuffEnum: int { New = 0, Old = 1, Fresh = 2 } 

How can I scroll it so that I can copy both the key and its value in one cycle? Something like:

 foreach(var item in stuffEnum) { NewObject thing = new NewObject{ Name = item.Key, Number = item.Value } } 

Thus, you will have 3 objects, their Name properties are set to "New", "Old" and "Fresh", and the "Number" properties are 0, 1 and 2.

How to do it?

+7
c #
source share
3 answers

The Enum class has the methods you are looking for.

 foreach(int i in Enum.GetValues(typeof(stuff))) { String name = Enum.GetName(typeof(stuff), i); NewObject thing = new NewObject { Name = name, Number = i }; } 
+10
source share

You can use LINQ (as always):

 List<NewObject> stuff = Enum.GetValues(typeof(stuffEnum)).Cast<stuffEnum>() .Select(s => new NewObject { Name = s.ToString(), Number = (int) s }) .ToList(); 
+7
source share
 foreach (var enumValue in Enum.GetValues(typeof(StuffEnum))) { Console.WriteLine("Name: {0}, Value: {1}", enumValue, (int)enumValue); } 

leads to

 Name: New, Value: 0 Name: Old, Value: 1 Name: Fresh, Value: 2 
+3
source share

All Articles