Getting values ​​from an enumeration

I have some code that sets up a dictionary with some defualt values ​​to enumerate:

foreach (string status in Enum.GetNames(typeof(TargetStatusType)))
{
    dict.Add((TargetStatusType)Enum.Parse(typeof(TargetStatusType), status), 0);
}

      

Is there an easier way to do this as it seems a little messy.

I was hoping I could just do

foreach(TargetStatusType status in ?) ...

      

Thanks!

+1


a source to share


3 answers


Use Enum.GetValues()

:

foreach (TargetStatusType type in Enum.GetValues(typeof(TargetStatusType)))

      



Note that although GetValues()

declared as returnable Array

, the loop foreach

does an automatic translation. Alternatively, you can apply the result to TargetStatusType[]

if you want to use it in another loop, in which casting each value would be awkward.

+4


a source


First, there is no need to use a dictionary here (or create any new collection for that matter). Also, getting the names of the enum values ​​and then parsing them is a terribly confusing technique when you can just call GetValues

.

The following should do the following task:



foreach(var status in Enum.GetValues(typeof(TargetStatusType))
    .Cast<TargetStatusType>())
{
    // ...
}

      

Calling an extension method Cast

means that your variable is status

strongly typed (of type TargetStatusType

), not just type object

.

+1


a source


if it is a dictionary initialization (no values ​​added earlier) you can also use linq dict = Enum.GetValues ​​(typeof (TargetStatusType)). ToDictinary (en => en, x => 0)

but I can't help but wonder why you would add them to the dictionary. you may have very good reasons :) I'm wondering because the value is the same. If to look up the index of an array with an int enum value will be much faster than a dictionary. if you don't care about the value and only want to add the key once, you can use Hashset <> instead

+1


a source







All Articles