You also can use the HasFlag
-method of the Enum
-class. As Henk pointed out will need to assign the values to your enum manually using values of the powers-of-2 sequence.
[Flags]
private enum MyEnum
{
Apple = 1,
Orange = 2,
Tomato = 4,
Potato = 8,
Melon 16,
Watermelon = 32,
Fruit = Apple | Orange,
Vegetable = Tomato | Potato,
Berry = Melon | Watermelon,
}
Then, to check you could use the following method which is working for all composed parts of your enumeration:
void Cheking(string data)
{
// Get the enum value of the string passed to the method
MyEnum myEnumData;
if (Enum.TryParse<MyEnum>(data, out myEnumData))
{
// If the string was a valid enum value iterate over all the value of
// the underlying enum type
var values = Enum.GetValues(typeof(MyEnum)).OfType<MyEnum>();
foreach (var value in values)
{
// If the value is not a power of 2 it is a composed one. If it furthermore
// has the flag passed to the method this is one we searched.
var isPowerOfTwo = (value != 0) && ((value & (value - 1)) == 0);
if (!isPowerOfTwo && value.HasFlag(myEnumData))
{
MessageBox.Show(value.ToString());
}
}
}
// In case an invalid value had been passed to the method
// display an error message.
else
{
MessageBox.Show("Invalid Value");
}
}
Or to write it in a shorter way using LINQ:
var results = Enum.GetValues(typeof(MyEnum))
.OfType<MyEnum>()
.Select(x => new { Value = x, IsPowerOfTwo = (x != 0) && ((x & (x - 1)) == 0) } )
.Where(x => !x.IsPowerOfTwo && x.Value.HasFlag(myEnumData))
.Select(x => x.Value.ToString());
This will give an IEnumerable<string>
containing the results. In case that myEnumData
has a value of MyEnum.Apple
the result will contain just the value "Fruit"
.