Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a C# enum's keys AND values [duplicate]

Tags:

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?

like image 382
yesman Avatar asked Nov 12 '14 12:11

yesman


People also ask

How do I loop through an array in C?

To iterate over Array using While Loop, start with index=0, and increment the index until the end of array, and during each iteration inside while loop, access the element using index.

What is a for loop in C?

The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

Can you loop through an array?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

How many types of loop are there in C?

C programming has three types of loops: for loop.


1 Answers

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
    };
}
like image 89
democore Avatar answered Sep 19 '22 15:09

democore