37
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?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Freephone Panwal
  • 1,547
  • 4
  • 21
  • 39
  • If you prefer a more generic implementation, [You can find it here](https://stackoverflow.com/a/47545368/3436775) . – Ozesh Nov 29 '17 at 05:07

4 Answers4

41

What about Enum.GetNames?

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

Give it a try ;)

Sylker Teles
  • 529
  • 4
  • 3
36

Use GetValues

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

Live demo

James
  • 80,725
  • 18
  • 167
  • 237
9

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

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
3

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();
Community
  • 1
  • 1
bowlturner
  • 1,968
  • 4
  • 23
  • 35