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 to share