1

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!

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.