Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
Raghav Avatar asked Dec 06 '25 03:12

Raghav


2 Answers

You can try doing this

foreach (MyColor value in Enum.GetValues(sum.GetType()))
    if (sum.HasFlag(value))
        //Here it is, do something with it
like image 125
David Pilkington Avatar answered Dec 07 '25 20:12

David Pilkington


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

like image 45
Irshad Avatar answered Dec 07 '25 20:12

Irshad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!