0

I have this enum:

public enum PPossumResp
{
    [EnumName("No Dyspnea")]
    NoDyspnea = 1,

    [EnumName("Dyspnea On Exertion")]
    DyspneaOnExertion = 2,

    [EnumName("Mild COPD on CXR")]
    MildCOPDonCXR = 2,

    [EnumName("Limited Dyspnea")]
    LimitedDyspnea = 4,

    [EnumName("Moderate COPD")]
    ModerateCOPD = 4,

    [EnumName("Dyspnea At Rest")]
    DyspneaAtRest = 8,

    [EnumName("Fibrosis")]
    Fibrosis = 8
}

and I am trying to populate a List with all the EnumName attributes.

I have this method that tries to do it:

public EnumPickerViewModel(Parameter param)
{
    this.param = param;
    List<string> enumNames = new List<string>();

    foreach(Enum type in Enum.GetValues(param.Value.GetType()))
    {
        enumNames.Add(Utils.GetEnumName(type));
    }
}

Unfortunately, enumNames is populated with the following: 0: No Dyspnea 1: Dyspnea on Exertion 2: Mild COPD on CXR 3: Limited Dyspnea 4: Limited Dyspnea 5: Dyspnea at Rest 6: Dyspnea at Rest

Since Limited Dyspnea and Moderate COPD have the same value of 4, and Dyspnea at Rest and Fibrosis have the same value of 8, it looks like Enum.GetValues() only gets the first value and takes that string attribute. How can I get all of the enum names despite repeated values?

i3arnon
  • 113,022
  • 33
  • 324
  • 344
BBH1023
  • 515
  • 2
  • 7
  • 18

1 Answers1

0

You can't do st. like that, Refer to this question for more info: Non-unique enum values

But as a workaround I can suggest you to use [Flags] attribute. The enum definition will be st. like this:

[Flags]
public enum PPossumResp
{
    NoDyspnea = 1,

    DyspneaOnExertion = 2,

    MildCOPDonCXR = 4,

    LimitedDyspnea = 8,

    ModerateCOPD = 16,

    DyspneaAtRest = 32,

    Fibrosis = 64
}

and you can use it like this:

    PPossumResp values = (PPossumResp)(4 | 8);

So if you get string representation of values like values.ToString() the output will be like this:

Output:

"MildCOPDonCXR, LimitedDyspnea"
Community
  • 1
  • 1
Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21
  • I need the string EnumNames. For this particular enum the names are similar to the strings, but in others they are very different, including special characters, numbers, etc – BBH1023 Jan 05 '14 at 05:42
  • For that you can write a simple *switch* statement to get the string representation of your enum or you may see this useful: http://stackoverflow.com/questions/630803/associating-enums-with-strings-in-c-sharp – Arin Ghazarian Jan 05 '14 at 06:05