Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Convert list of enum values to list of strings

Tags:

c#

enums

Let's say I have a C# enum called MyEnum:

public enum MyEnum
{
    Apple,
    Banana,
    Carrot,
    Donut
}

And I have a List<MyEnum> such as:

List<MyEnum> myList = new List<MyEnum>();
myList.Add(MyEnum.Apple);
myList.Add(MyEnum.Carrot);

What is the easiest way to convert my List<MyEnum> to a List<string>? Do I have to create a new List<string> and then iterate through the enum list, one item at a time, converting each enum to a string and adding it to my new List<string>?

like image 712
BlueTriangles Avatar asked Jan 02 '23 07:01

BlueTriangles


1 Answers

Since you are using a List, the easiest solution would be to use the ConvertAll method to obtain a new List containing string representations. Here's an example:

List<string> stringList = myList.ConvertAll(f => f.ToString());

There are other ways to accomplish this, but this way will get the job done and uses syntax that should be in whatever version of .NET you're using because it's been around for a long time.

like image 108
Kyle Burns Avatar answered Jan 14 '23 15:01

Kyle Burns