0

In the following example I would like to add flavours that start with "APPLE" to a ComboBox on a form. When the enums have unique values it works fine; however, in my example two enums PINEAPPLE_PEACH and APPLE_ORANGE both have a value of 1 and this messes up the results.

Is it erroneous to have two enums with the same value and, if so, how can I change my code to get consistent results?

    public enum Flavour
    {
        APPLE_PEACH = 0,
        PINEAPPLE_PEACH = 1,
        APPLE_ORANGE = 1,
        APPLE_BANANA = 3,
        PINEAPPLE_GRAPE = 4
    }

    private void AddFlavours()
    {
        foreach (Flavour flavour in Enum.GetValues(typeof(Flavour)))
        {
            string flavourName = Enum.GetName(typeof(Flavour), flavour);
            if (flavourName.StartsWith("APPLE"))
            {
                myComboBox.Items.Add(flavour);
            }
        }
    }
eft
  • 2,509
  • 6
  • 26
  • 24
  • You can use iteration described by Konamiman. But anyway, why do you ever need duplicates in enum values? – terR0Q Nov 20 '09 at 08:55
  • it's actually an enum from a third-party library so I have no choice :). Above code is for illustration purposes. – eft Nov 20 '09 at 15:21
  • Possible duplicate of [enum to comboBox except some of enum elements](http://stackoverflow.com/questions/35047167/enum-to-combobox-except-some-of-enum-elements) – Eulogy Jan 28 '16 at 03:49

2 Answers2

1

With Linq, you may use this:

foreach (string flavourName in Enum.GetNames(typeof(Flavour)).Where(s => s.StartsWith("APPLE")))     
{
    myComboBox.Items.Add(flavourName);
}
Thomas Weller
  • 11,631
  • 3
  • 26
  • 34
0

You can use Enum.GetNames instead of GetValues. It would be something like this (not tested):

 foreach (string flavourName in Enum.GetNames(typeof(Flavour)))
 {
     if (flavourName.StartsWith("APPLE"))
     {
         myComboBox.Items.Add(Enum.Parse(typeof(flavour), flavourName));
     }
 }
Konamiman
  • 49,681
  • 17
  • 108
  • 138