Enum index by value

 [FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

      

I have a listing as a show. I want you to be able to say Colors.Blue is index 2, index looking at 0. I want to get the index number going through Colors. Howbeit? Can someone post me some snippets ...

+2


source to share


7 replies


Assuming each color uses one bit as a value, you can simply find the index of that bit.

public int GetIndex(Colors color) {
   int value = (int)colors;
   int index = 0;
   while (value > 0) {
      value >>= 1;
      index++;
   }
   return index;
}

      



Note that the bit index is usually zero, but you get one base index here.

If you want a zero-based index, you will get index two for blue, not three as you said in the question. Just start with index = -1;

if that's the result you want.

+3


source


Try the following:



int index  = Array.IndexOf(Enum.GetValues(typeof(Colors )), Colors.Green);

      

+11


source


Can't understand your question, but this is what you mean:

var blue = (Colors)Enum.GetValues(typeof(Colors))[2];

      

+2


source


I don't know why you need this, but one way to do it

 Colors c = (Colors)Enum.Parse(typeof(Colors), Enum.GetNames(typeof(Colors))[index]);

      

+1


source


This is the easiest solution I have found. Works great with flags without worrying about byte operations.

Array eVals = Enum.GetValues(typeof(MyEnum));
MyEnum eVal = (MyEnum)eVals.GetValue(iIndex);

      

0


source


I got this working after this:

return (Status)Enum.GetValues(typeof(Status)).GetValue(this.EvaluationStatusId);

      

0


source


I am using the following code and it works:

 int index=(int)Enum.Parse(typeof(Colors), "Green");

      

0


source







All Articles