Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General method to convert enum to List<T> [duplicate]

Tags:

c#

Here's a "weird" question:

Is it possible to create a method where in it will convert whatever enum to list. Here's my draft of what I'm currently thinking.

public class EnumTypes
{
   public enum Enum1
   {
      Enum1_Choice1 = 1,
      Enum1_Choice2 = 2
   }

   public enum Enum2
   {
      Enum2_Choice1 = 1,
      Enum2_Choice2 = 2
   }

   public List<string> ExportEnumToList(<enum choice> enumName)
   {
      List<string> enumList = new List<string>();
      //TODO: Do something here which I don't know how to do it.
      return enumList;
   }
}

Just curious if it's possible and how to do it.

like image 367
Musikero31 Avatar asked Apr 02 '13 06:04

Musikero31


People also ask

How do I turn an enum into a list?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

How do I get all the values in an enum list?

Use a list comprehension to get a list of all enum values, e.g. values = [member. value for member in Sizes] . On each iteration, access the value attribute on the enum member to get a list of all of the enum's values. Copied!

Can enum have duplicate values?

CA1069: Enums should not have duplicate values (code analysis) - .

Can enum be subclassed?

You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.


1 Answers

Enum.GetNames( typeof(EnumType) ).ToList()

http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx

Or, if you want to get fancy:

    public static List<string> GetEnumList<T>()
    {
        // validate that T is in fact an enum
        if (!typeof(T).IsEnum)
        {
            throw new InvalidOperationException();
        }

        return Enum.GetNames(typeof(T)).ToList();
    }

    // usage:
    var list = GetEnumList<EnumType>();
like image 131
Moho Avatar answered Sep 30 '22 15:09

Moho