tags:

views:

106

answers:

2

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);
            }
        }
    }
A: 

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
You need to change Flavour to string.
Taylor Leese
+1  A: 

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