3

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?

2 Answers 2

3

You can try doing this

foreach (MyColor value in Enum.GetValues(sum.GetType()))
    if (sum.HasFlag(value))
        //Here it is, do something with it
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.