简体   繁体   中英

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

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

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.

var list= (from action in (MyEnum[]) Enum.GetValues(typeof(MyEnum)) select action.ToString()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM