枚举到comboBox,除了一些枚举元素

时间:2016-01-27 20:15:28

标签: c#

例如我有枚举:

private enum Categories
{
foo,
fooBar,
Bar
}

这样我就按枚举元素填充comboBox:

myComboBox.ItemsSource = Enum.GetValues(typeof(Categories)).Cast<Categories>();

但是如何绑定枚举除Categories.fooBar以外的所有元素?

2 个答案:

答案 0 :(得分:3)

您可以使用Where

Enum.GetValues(typeof(Categories))
      .Cast<Categories>()
      .Where(x => x != Categories.fooBar).ToList();

答案 1 :(得分:2)

使用 除外():如果需要添加例外,则只需将这些项添加到列表中除了值或内联声明中。

var exceptValues = new[] {Categories.fooBar};
var source = Enum.GetValues(typeof(Categories)).Cast<Categories>().Except(exceptValues);

或者

var source = Enum.GetValues(typeof(Categories)).Cast<Categories>().Except( new[] {Categories.fooBar})

干杯。