¿Cómo convierto una enumeración en una lista en C#? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Hay alguna manera de convertir un enum a una lista que contenga todas las opciones de la enumeración?

 500
Author: abatishchev, 2009-07-22

14 answers

Esto devolverá un IEnumerable<SomeEnum> de todos los valores de una Enumeración.

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

Si quieres que sea un List<SomeEnum>, simplemente agrega .ToList() después de .Cast<SomeEnum>().

Para usar la función Cast en un Array necesitas tener el System.Linq en tu sección using.

 850
Author: Jake Pearson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-24 15:18:04

Mucho más fácil:

Enum.GetValues(typeof(SomeEnum))
    .Cast<SomeEnum>()
    .Select(v => v.ToString())
    .ToList();
 77
Author: Gili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-19 23:44:53

La respuesta corta es, use:

(SomeEnum[])Enum.GetValues(typeof(SomeEnum))

Si necesitas eso para una variable local, es var allSomeEnumValues = (SomeEnum[])Enum.GetValues(typeof(SomeEnum));.

¿Por qué la sintaxis es así?!

El método staticGetValues se introdujo en el antiguo. NET 1.0 días. Devuelve un array unidimensional de tipo runtime SomeEnum[]. Pero dado que es un método no genérico (generics no se introdujo hasta.NET 2.0), no puede declarar su tipo de retorno (tipo de retorno en tiempo de compilación) como tal.

Los arrays. NET tienen un tipo de covarianza, sino porque SomeEnum será un tipo de valor, y debido a que la covarianza del tipo de matriz no funciona con los tipos de valor, ni siquiera pudieron declarar el tipo devuelto como object[] o Enum[]. (Esto es diferente de, por ejemplo, esta sobrecarga de GetCustomAttributes de.NET 1.0 que tiene un tipo de retorno en tiempo de compilación object[] pero en realidad devuelve una matriz de tipo SomeAttribute[] donde SomeAttribute es necesariamente un tipo de referencia.)

Debido a esto, el método. NET 1.0 tuvo que declarar su devuelve el tipo como System.Array. Pero te garantizo que es un SomeEnum[].

Cada vez que llame a GetValues de nuevo con el mismo tipo de enumeración, tendrá que asignar un nuevo array y copiar los valores en el nuevo array. Esto se debe a que los arrays pueden ser escritos (modificados) por el "consumidor" del método, por lo que tienen que hacer un nuevo array para asegurarse de que los valores no cambian. . NET 1.0 no tenía buenas colecciones de solo lectura.

Si necesita la lista de todos los valores en muchos lugares diferentes, considere llamar GetValues solo una vez y almacenar en caché el resultado en un wrapper de solo lectura, por ejemplo así:

public static readonly ReadOnlyCollection<SomeEnum> AllSomeEnumValues
    = Array.AsReadOnly((SomeEnum[])Enum.GetValues(typeof(SomeEnum)));

Entonces puede usar AllSomeEnumValues muchas veces, y la misma colección se puede reutilizar de forma segura.

¿Por qué es malo usar .Cast<SomeEnum>()?

Muchas otras respuestas usan .Cast<SomeEnum>(). El problema con esto es que utiliza la implementación no genérica IEnumerable de la clase Array. Este debería haber incluido cada uno de los valores en un cuadro System.Object, y luego usar el Cast<> método para descomprimir todos esos valores de nuevo. Afortunadamente, el método .Cast<> parece verificar el tipo de tiempo de ejecución de su parámetro IEnumerable (el parámetro this) antes de comenzar a iterar a través de la colección, por lo que no es tan malo después de todo. Resulta que .Cast<> deja pasar la misma instancia de matriz.

Si lo sigues por .ToArray() o .ToList(), como en:

Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList() // DON'T do this

Tiene otro problema: Crea una nueva colección (array) cuando llama a GetValues y luego crea una nueva colección (List<>) con la llamada .ToList(). Por lo que es una (extra) asignación redundante de una colección entera para contener los valores.

 63
Author: Jeppe Stig Nielsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-06 19:41:56

Aquí está la forma en que amo, usando LINQ:

public class EnumModel
{
    public int Value { get; set; }
    public string Name { get; set; }
}

public enum MyEnum
{
    Name1=1,
    Name2=2,
    Name3=3
}

public class Test
{
    List<EnumModel> enums = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => new EnumModel() { Value = (int)c, Name = c.ToString() }).ToList();
}

Espero que ayude

 24
Author: Booster2ooo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 06:34:45
List <SomeEnum> theList = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();
 19
Author: luisetxenike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-14 19:58:24

Respuesta muy simple

Aquí hay una propiedad que uso en una de mis aplicaciones

public List<string> OperationModes
{
    get
    {
       return Enum.GetNames(typeof(SomeENUM)).ToList();
    }
}
 10
Author: Tyler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 16:08:30

Siempre he utilizado para obtener una lista de enum valores como este:

Array list = Enum.GetValues(typeof (SomeEnum));
 5
Author: Claudiu Constantin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-31 07:41:08

Aquí para su utilidad... algún código para obtener los valores en una lista, que convierte la enumeración en una forma legible para el texto

public class KeyValuePair
  {
    public string Key { get; set; }

    public string Name { get; set; }

    public int Value { get; set; }

    public static List<KeyValuePair> ListFrom<T>()
    {
      var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
      return array
        .Select(a => new KeyValuePair
          {
            Key = a.ToString(),
            Name = a.ToString().SplitCapitalizedWords(),
            Value = Convert.ToInt32(a)
          })
          .OrderBy(kvp => kvp.Name)
         .ToList();
    }
  }

.. y el Sistema de apoyo.Método de extensión de cadena:

/// <summary>
/// Split a string on each occurrence of a capital (assumed to be a word)
/// e.g. MyBigToe returns "My Big Toe"
/// </summary>
public static string SplitCapitalizedWords(this string source)
{
  if (String.IsNullOrEmpty(source)) return String.Empty;
  var newText = new StringBuilder(source.Length * 2);
  newText.Append(source[0]);
  for (int i = 1; i < source.Length; i++)
  {
    if (char.IsUpper(source[i]))
      newText.Append(' ');
    newText.Append(source[i]);
  }
  return newText.ToString();
}
 5
Author: jenson-button-event,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-13 18:49:26
Language[] result = (Language[])Enum.GetValues(typeof(Language))
 4
Author: Shyam sundar shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-15 12:37:18
public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<NameValue> EnumToList<T>()
{
    var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
    var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
    List<NameValue> lst = null;
    for (int i = 0; i < array.Length; i++)
    {
        if (lst == null)
            lst = new List<NameValue>();
        string name = array2[i];
        T value = array[i];
        lst.Add(new NameValue { Name = name, Value = value });
    }
    return lst;
}

Convertir Enumeración A una lista más información disponible aquí.

 2
Author: Kiarash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 14:49:49
/// <summary>
/// Method return a read-only collection of the names of the constants in specified enum
/// </summary>
/// <returns></returns>
public static ReadOnlyCollection<string> GetNames()
{
    return Enum.GetNames(typeof(T)).Cast<string>().ToList().AsReadOnly();   
}

Donde T es un tipo de Enumeración; Añadir esto:

using System.Collections.ObjectModel; 
 1
Author: frigate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-01 05:40:18

Si desea Enum int como clave y nombre como valor, bien si almacena el número en la base de datos y es de Enum!

void Main()
{
     ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<SearchDataType>();

     foreach (var element in list)
     {
        Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
     }

     /* OUTPUT:
        Key: 1; Value: Boolean
        Key: 2; Value: DateTime
        Key: 3; Value: Numeric         
     */
}

public class EnumValueDto
{
    public int Key { get; set; }

    public string Value { get; set; }

    public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("Type given T must be an Enum");
        }

        var result = Enum.GetValues(typeof(T))
                         .Cast<T>()
                         .Select(x =>  new EnumValueDto { Key = Convert.ToInt32(x), 
                                       Value = x.ToString(new CultureInfo("en")) })
                         .ToList()
                         .AsReadOnly();

        return result;
    }
}

public enum SearchDataType
{
    Boolean = 1,
    DateTime,
    Numeric
}
 1
Author: xajler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-19 15:48:13
private List<SimpleLogType> GetLogType()
{
  List<SimpleLogType> logList = new List<SimpleLogType>();
  SimpleLogType internalLogType;
  foreach (var logtype in Enum.GetValues(typeof(Log)))
  {
    internalLogType = new SimpleLogType();
    internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
    internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
    logList.Add(internalLogType);
  }
  return logList;
}

En el código superior , Log es una enumeración y SimpleLogType es una estructura para logs .

public enum Log
{
  None = 0,
  Info = 1,
  Warning = 8,
  Error = 3
}
 1
Author: Mohammad Eftekhari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-05 11:01:57

Podría usar el siguiente método genérico:

public static List<T> GetItemsList<T>(this int enums) where T : struct, IConvertible
{
    if (!typeof (T).IsEnum)
    {
        throw new Exception("Type given must be an Enum");
    }

    return (from int item in Enum.GetValues(typeof (T))
            where (enums & item) == item
            select (T) Enum.Parse(typeof (T), item.ToString(new CultureInfo("en")))).ToList();
}
 0
Author: Vitall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-28 10:53:51