I have the following enum:
[Flags]
public enum MyColor
{
None = 0,
Red = 1,
Green = 2,
Blue = 4,
Orange = 8
}
I am storing the sum of allowed options in a variable say:
var sum = MyColor.Red | MyColor.Green | MyColor.Blue;
I want to extract the options back from this sum.
i.e I want to know which values are contained in this sum.I want the collection of options Red, Green and Blue from this variable back.
Can you help me doing that?
You can try doing this
foreach (MyColor value in Enum.GetValues(sum.GetType()))
if (sum.HasFlag(value))
//Here it is, do something with it
Improving on David Pilkington's answer;
var colorCollection = new List<MyColor>();
var colorValues = Enum.GetValues(typeof(MyColor));
foreach (var color in colorValues)
if(sum.HasFlag(color))
colorCollection.Add(color);
More on HasFlag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With