Converting enum values into an string array

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?

Answers


Use GetValues

Enum.GetValues(typeof(VehicleData))
    .Cast<int>()
    .Select(x => x.ToString())
    .ToArray();

Live demo


What about Enum.GetNames?

string[] cars = System.Enum.GetNames( typeof( VehicleData ) );

Give it a try ;)


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();

Demo


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();

Need Your Help

How can I use .htaccess to hide .php URL extensions?

php regex apache .htaccess mod-rewrite

I want something to put in my .htaccess file that will hide the .php file extension for my php files, so going to www.example.com/dir/somepage would show them www.example.com/dir/somepage.php.

Changing names of parameterized tests

java junit junit4 parameterized

Is there a way to set my own custom test case names when using parameterized tests in JUnit4?