Reputation: 23014
It's very easy I have the following Enum
Public Enum TCheckStatus
Checked
NotChecked
Indeterminate
End Enum
I want to get the Index of the given name found in the enum, what's the best way?!!
For Example:
Suppose I have "NotChecked" string , I want the output to be 1
Upvotes: 1
Views: 5365
Reputation: 11
int Output = (int)Enum.Parse(typeof(TCheckStatus), "NotChecked");
Upvotes: 1
Reputation: 263723
try this:
Dim val as integer = cint(DirectCast([Enum].Parse(GetType(TCheckStatus), _
"NotChecked"), TCheckStatus)
StackOverflow - Parse a string to an Enum value in VB.NET
Upvotes: 1
Reputation: 460108
You are looking for Enum.GetNames. It retrieves an array of the names of the constants in a specified enumeration.
Dim notCheckedStatus = DirectCast([Enum].Parse(GetType(TCheckStatus), "NotChecked"), TCheckStatus)
Dim allStatusNames = [Enum].GetNames(GetType(TCheckStatus))
Dim indexOfNotChecked = Array.IndexOf(AllStatusNames, "NotChecked") '=1'
string
variable to an enum-valueArray
Array
Of course to solve your question you only need this:
Array.IndexOf([Enum].GetNames(GetType(TCheckStatus)), "NotChecked")
Upvotes: 2
Reputation: 965
To get arrays of the names and their integer equivalents with the Enum methods in VB.net, please use GetNames() and GetValues() method. Use Parse() to get the index. Hope this helps.
Upvotes: 1
Reputation: 60694
I can't give precise vb syntax, but I'll write it in C# so see if you can use it:
int index = (int)Enum.Parse( typeof(TCheckStatus), "NotChecked");
index
is 1 in this case. If you give an invalid string (not a member of the enum), it will throw an exception. If this is not what you want, you can use Enum.TryParse
instead.
If you already have the enum, you can just cast it to a int to get the index:
var myEnum = TCheckStatus.NotChecked;
int index = (int)myEnum;
Upvotes: 2