Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting enum values into an string array

Tags:

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?

like image 437
Freephone Panwal Avatar asked Aug 04 '14 19:08

Freephone Panwal


People also ask

Can enum be converted to string?

We can convert an enum to string by calling the ToString() method of an Enum.

Can an enum be an array?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.

How do I convert an enum to a string in Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can we convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.


2 Answers

What about Enum.GetNames?

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

Give it a try ;)

like image 175
Sylker Teles Avatar answered Oct 15 '22 03:10

Sylker Teles


Use GetValues

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

Live demo

like image 40
James Avatar answered Oct 15 '22 02:10

James