[FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
I have an enum as show. I want the ability to get say Colors.Blue is at index 2, index staring from 0.I want to get the index number passing in Colors.Whatever? Can someone post me some snippets...
Try this one:
int index = Array.IndexOf(Enum.GetValues(typeof(Colors )), Colors.Green);
Assuming that each color uses a single bit as value, you can just locate 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 index of bits is normally zero based, but here you get a one based index.
If you want a zero based index, you would get the index two for blue, not three as you stated in the question. Just start with index = -1; if that is the result that you desire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With