I have two enums:
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 3,
Blueberry = 4
}
public enum FruitsCombined
{
Apple = 1,
Banana = 2,
Berries = 0 //Strawberry and Blueberry combined
}
I have a Combobox, which is bound to the FruitsCombined
enum, but in the background, when I select Berries
, I want to say it's 3 and 4 from the Fruits
enum.
How can I do this?
For example, I want to replace this for a better way, with the two enums:
if ((int)cboFilterFruitType.SelectedValue == 0)
{
order = order.FindAll(o => o.FruitID == 3 || o.FruitID == 4);
}
else
{
order = order.FindAll(o => o.FruitID == (int) cboFilterFruitType.SelectedValue);
}
CodePudding user response:
You can use flags
enums:
[Flags]
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8
}
public enum FruitsCombined
{
Apple = 1,
Banana = 2,
Berries = Fruits.Strawberry | Fruits.Blueberry //Strawberry and Blueberry combined
}
Now you can cast one to the other:
FruitsCombined fruitCombined = FruitsCombined.Berries;
Fruits fruit = (Fruits)fruitCombined; // Fruits.Strawberry | Fruits.Blueberry
If you want to check if it's a berry you can use Enum.HasFlag
:
bool isBerry = fruit.HasFlag(Fruits.Strawberry | Fruits.Blueberry);
CodePudding user response:
If you have control over both enums you could combine the enums together using flags like suggested in the comments.
[Flags]
public enum Fruits
{
None = 0,
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8,
Berries = Strawberry | Blueberry
}
Then if you had code like this
var fruit = Fruits.Berries;
Console.WriteLine(fruit.HasFlag(Strawberry));
Console.WriteLine(fruit.HasFlag(Blueberry));
Both write lines would print true.
CodePudding user response:
as stuartd link says do something more like
change to powers of two
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8
}
Then you can use bitwise to represent any combo
var appBann = Fruits.Apple | Suits.Banana ;
or Berries = Fruits.Strawberry | Suits.Blueberry
you can even have it as a enum
public enum Fruits
{
Apple = 1,
Banana = 2,
Strawberry = 4,
Blueberry = 8,
Berries = Strawberry | Blueberry
}
order = order.FindAll(o => o.FruitID == (int)Fruits.Berries);