Freephone Panwal
Freephone Panwal

Reputation: 1591

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?

Upvotes: 39

Views: 57908

Answers (4)

Sylker Teles
Sylker Teles

Reputation: 569

What about Enum.GetNames?

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

Give it a try ;)

Upvotes: 44

bowlturner
bowlturner

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

Matt Burland
Matt Burland

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

Demo

Upvotes: 9

James
James

Reputation: 82096

Use GetValues

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

Live demo

Upvotes: 37

Related Questions