如何将一些枚举值添加到组合框中 [英] How can I add some Enum values to a combobox

查看:204
本文介绍了如何将一些枚举值添加到组合框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我想添加以APPLE开头的风格到窗体上的ComboBox。当枚举具有唯一的值时,它工作正常;然而,在我的示例中,两个枚举PINEAPPLE_PEACH和APPLE_ORANGE都有一个值为1,这样会使结果混乱。

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


推荐答案

使用Linq,您可以使用以下内容:

With Linq, you may use this:

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

这篇关于如何将一些枚举值添加到组合框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆