Raghav
Raghav

Reputation: 9630

Getting values back from enum sum

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?

Upvotes: 3

Views: 1076

Answers (2)

Irshad
Irshad

Reputation: 3131

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

Upvotes: 2

David Pilkington
David Pilkington

Reputation: 13620

You can try doing this

foreach (MyColor value in Enum.GetValues(sum.GetType()))
    if (sum.HasFlag(value))
        //Here it is, do something with it

Upvotes: 3

Related Questions