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

1
  • If you prefer a more generic implementation, You can find it here . Commented Nov 29, 2017 at 5:07

4 Answers 4

43

What about Enum.GetNames?

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

Give it a try ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Enum.GetNames returns array of string not a single string
System.Enum.GetNames will give names and not values as OP as asked for.
38

Use GetValues

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

Live demo

Comments

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

1 Comment

It seems as though your demo doesn't correspond to your shown example.
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.