Home > Enterprise >  How to store enum values in an array of integer in c# using for or foreach loop? [duplicate]
How to store enum values in an array of integer in c# using for or foreach loop? [duplicate]

Time:10-01

I would like to store enum values to an array of interger,

enum timeSlots
        {
            AM9h = 0,
            AM10h = 1,
            AM11h = 2,
            AM12h = 3,
            PM1h = 4,
            PM2h = 5,
            PM3h = 6,
            PM4h = 7,
            PM5h = 8,
            PM6h = 9,
        }

how can I store timeslots enum's value to an int array?

CodePudding user response:

Well... you can't really. C# is strongly-typed, after all, so any integer array is always going to store integers.

Now what you can do is cast an enum to an int when you want to store it in one of the array elements, and cast it back to the enum type when you need it again. Or you can declare an array of your enum type.

CodePudding user response:

Use list instead.

    var nrList = new List<int>();

    foreach (var e in timeSlots)
    {
     nrList.add((int)e);
    }

CodePudding user response:

Looks like what you're looking for is Enum.GetValues. Here's an example:

var enums = Enum.GetValues(typeof(timeSlots));
var count = enums.Length;
var array = new int[count];

for(var i = 0; i < count; i  )
    array[i] = enums[i];          

Not on a computer, so can't test it out right now. Hope it gives you some direction.

  • Related