Reputation: 1591
public enum VehicleData
{
Dodge = 15001,
BMW = 15002,
Toyota = 15003
}
I want to get above values 15001, 15002, 15003 in string array as shown below:
string[] arr = { "15001", "15002", "15003" };
I tried below command but that gave me array of names instead of values.
string[] aaa = (string[]) Enum.GetNames(typeof(VehicleData));
I also tried string[] aaa = (string[]) Enum.GetValues(typeof(VehicleData));
but that didn't work too.
Any suggestions?
Upvotes: 39
Views: 57908
Reputation: 569
What about Enum.GetNames?
string[] cars = System.Enum.GetNames( typeof( VehicleData ) );
Give it a try ;)
Upvotes: 44
Reputation: 2016
I found this here - How do I convert an enum to a list in C#?, modified to make array.
Enum.GetValues(typeof(VehicleData))
.Cast<int>()
.Select(v => v.ToString())
.ToArray();
Upvotes: 3
Reputation: 45135
Enum.GetValues
will give you an array with all the defined values of your Enum
. To turn them into numeric strings you will need to cast to int
and then ToString()
them
Something like:
var vals = Enum.GetValues(typeof(VehicleData))
.Cast<int>()
.Select(x => x.ToString())
.ToArray();
Upvotes: 9