Reputation:
I'm new in c#. I want to know the how to convert the result of the method Enum.GetValues() into the array of string? This is my code :
using System;
using System.Linq;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
foreach (var item in Enum.GetValues(typeof(MyEnumList)))
Console.WriteLine(item);
}
}
public enum MyEnumList
{
egg, apple, orange, potato
}
}
Now I don't want to have foreach on the result. I want to store the result as an string[] variable. Thank you.
Upvotes: 0
Views: 1786
Reputation: 16104
If you want an array of names, you can just use Enum.GetNames
Method
Retrieves an array of the names of the constants in a specified enumeration.
using System;
public class Program
{
public static void Main()
{
string[] names = Enum.GetNames(typeof(MyEnumList));
Console.WriteLine("[{0}]", string.Join(",", names));
}
}
public enum MyEnumList
{
egg, apple, orange, potato
}
[egg,apple,orange,potato]
If you want a string[]
of the numeric values:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] enumAsStrings = Enum.GetValues(typeof(MyEnumList)) // strongly typed values
.Cast<int>() // Get the _numeric_ values
.Select(x => x.ToString()) // conv. to string
.ToArray(); // give me an array
Console.WriteLine("[{0}]",string.Join(",", enumAsStrings));
}
}
public enum MyEnumList
{
egg, apple, orange, potato
}
[0,1,2,3]
Upvotes: 3
Reputation: 122
Probably you want something like that:
var enums = Enum.GetValues(typeof(MyEnumList)).Cast<MyEnumList>().Select(x=>x.ToString()).ToArray();
Upvotes: 0