tags:

views:

160

answers:

3

I have some code that sets up a dictionary with some defualt values for an enum:

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 bit messy.

I was hoping I could just do

foreach(TargetStatusType status in ?) ...

Thanks!

+4  A: 

Use Enum.GetValues():

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

Note that although GetValues() is only declared to return Array, the foreach loop performs the cast for you automatically. Alternatively you could cast the result to TargetStatusType[] if you wanted to use it in a different loop where casting each value would be inconvenient.

Jon Skeet
Pipped to the post yet again. :)
Noldorin
I knew there would be something obvious, thanks :)
Fiona
+1  A: 

Firstly, there's no need to use a dictionary here (or to create any sort of new collection for that matter). Also, getting the names of the enum values and then parsing them is a awfully convoluted method when you can just call GetValues.

The following should do the job:

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

The call to the Cast extension method means that your status variable is strongly-typed (of type TargetStatusType) rather than simply of type object.

Noldorin
+1  A: 

if this is the initialization of the dictionary (no prior values added) you could also use linq dict = Enum.GetValues(typeof(TargetStatusType)).ToDictinary(en => en,x => 0)

but I can't help wonder why you would add them to a dictionary. you might have very good reasons :) Im wondering because the value is the same. If it's for a lookup an array index with the int value of the enum will be a lot faster than the dictionary. if you don't care bout the value and only wanna enforce adding the key once, you could use a Hashset<> instead

Rune FS