Converting enum values ​​to an array of strings

public enum VehicleData { Dodge = 15001, BMW = 15002, Toyota = 15003 } 

I want to get the values ​​15001, 15002, 15003 in an array of strings, as shown below:

 string[] arr = { "15001", "15002", "15003" }; 

I tried the command below, but this gave me an 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 either.

Any suggestions?

+6
source share
4 answers

Use GetValues

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

Live demo

+18
source

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 specify int and then ToString() them

Sort of:

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

Demo

+7
source

I found this here - How to convert an enumeration to a list in C #? Modified to create an array.

 Enum.GetValues(typeof(VehicleData)) .Cast<int>() .Select(v => v.ToString()) .ToArray(); 
+3
source

What about Enum.GetNames names?

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

Try it;)

+3
source

Source: https://habr.com/ru/post/973337/


All Articles