Número total de elementos definidos en una enumeración


¿Cómo puedo obtener el número de elementos definidos en una enumeración?

 255
Author: Timothy Shields, 2009-05-13

9 answers

Puede utilizar el método estáticoEnum.GetNames que devuelve una matriz que representa los nombres de todos los elementos de la enumeración. La propiedad length de esta matriz es igual al número de elementos definidos en la enumeración

var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
 340
Author: Kasper Holdum,
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-05-04 12:24:57

La pregunta es:

¿Cómo puedo obtener el número de elementos definidos en una enumeración?

El número de "elementos" realmente podría significar dos cosas completamente diferentes. Considere el siguiente ejemplo.

enum MyEnum
{
    A = 1,
    B = 2,
    C = 1,
    D = 3,
    E = 2
}

¿Cuál es el número de "elementos" definidos en MyEnum?

¿Es el número de ítems 5? (A, B, C, D, E)

O es 3? (1, 2, 3)

El número de nombres definido en MyEnum (5) puede ser calculado como sigue.

var namesCount = Enum.GetNames(typeof(MyEnum)).Length;

El número de valores definidos en MyEnum (3) se puede calcular de la siguiente manera.

var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();
 157
Author: Timothy Shields,
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
2015-01-20 17:18:30

Enum.getValues (typeof (MyEnum)).Longitud;

 68
Author: Matt Hamilton,
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
2014-11-26 10:59:09

Un ingenioso truco que vi en una respuesta C a esta pregunta, simplemente agregue un último elemento a la enumeración y utilícelo para decir cuántos elementos hay en la enumeración:

enum MyType {
  Type1,
  Type2,
  Type3,
  NumberOfTypes
}

En el caso de que esté definiendo un valor inicial distinto de 0, puede usar NumberOfTypes - Type1 para determinar el número de elementos.

No estoy seguro de si este método sería más rápido que usar Enum, y tampoco estoy seguro de si se consideraría la forma correcta de hacer esto, ya que tenemos Enum para determinar esta información para nos.

 11
Author: Josh,
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-05 17:29:18

De las respuestas anteriores simplemente agregando ejemplo de código.

 class Program
    {
        static void Main(string[] args)
        {
            int enumlen = Enum.GetNames(typeof(myenum)).Length;
            Console.Write(enumlen);
            Console.Read();
        }
        public enum myenum
        {
            value1,
            value2
        }
    }
 6
Author: jvanderh,
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
2009-05-13 05:17:36

Puede usar Enum.GetNames para devolver un IEnumerable de valores en su enumeración y, a continuación,.Recuento de la resultante IEnumerable.

GetNames produce el mismo resultado que getValues pero es más rápido.

 5
Author: Lucas Willett,
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
2009-05-13 05:10:03

Si te encuentras escribiendo la solución anterior tan a menudo como yo, entonces podrías implementarla como un genérico:

public static int GetEnumEntries<T>() where T : struct, IConvertible 
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("T must be an enumerated type");

    return Enum.GetNames(typeof(T)).Length;
}
 2
Author: Matt Parkins,
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
2016-09-19 11:08:57

Estaba investigando esto hace un momento, y no estaba contento con la legibilidad de la solución actual. Si estás escribiendo código informalmente o en un proyecto pequeño, puedes simplemente agregar otro elemento al final de tu enumeración llamado "Length". De esta manera, solo necesita escribir:

var namesCount = (int)MyEnum.Length;

Por supuesto, si otros van a usar su código, o estoy seguro de que bajo muchas otras circunstancias que no se aplicaron a mí en este caso, esta solución puede ser desde mal aconsejada hasta terrible.

 1
Author: EnergyWasRaw,
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
2014-11-12 23:07:00

Para Visual Basic:

[Enum].GetNames(typeof(MyEnum)).Length no trabajó conmigo, pero [Enum].GetNames(GetType(Animal_Type)).length lo hizo.

 1
Author: S22,
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-02-22 19:01:18