开发者

How can I add some Enum values to a combobox

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


With Linq, you may use this:

foreach (string flavourName in Enum.GetNames(typeof(Flavour)).Where(s => s.StartsWith("APPLE")))     
{
    myComboBox.Items.Add(flavourName);
}


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));
     }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜