Friday, February 8, 2019

Loop through a C# enum's keys AND values




Given the C# enum:



public enum stuffEnum: int

{
New = 0,
Old = 1,
Fresh = 2
}


How do I loop through it in a way that I can copy both the key and its value in a single loop? Something like:



foreach(var item in stuffEnum)

{
NewObject thing = new NewObject{
Name = item.Key,
Number = item.Value
}
}


So you would end up with 3 objects, with their Name properties set to "New", "Old", and "Fresh", and the Number properties set to 0, 1 and 2.




How do I do this?


Answer



The Enum class has the Methods you're 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
};
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...