How can I get the number of items defined in an enum?
Use the len() class to get the number of elements in an enum, e.g. len(Color) . The len() function returns the length (the number of items) of an object and can directly be passed an enum. Copied! The len() function returns the length (the number of items) of an object.
There are multiple ways to check the size of an enum type. Second, using object methods keys() , values() , entries() methods to get the array list of keys, values, and key-value multiple constants. These methods return the array of enum constants. using the length method on the array, prints the size.
In theory, an ENUM column can have a maximum of 65,535 distinct values; in practice, the real maximum depends on many factors.
You can use the static method Enum.GetNames
which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
The question is:
How can I get the number of items defined in an enum?
The number of "items" could really mean two completely different things. Consider the following example.
enum MyEnum { A = 1, B = 2, C = 1, D = 3, E = 2 }
What is the number of "items" defined in MyEnum
?
Is the number of items 5? (A
, B
, C
, D
, E
)
Or is it 3? (1
, 2
, 3
)
The number of names defined in MyEnum
(5) can be computed as follows.
var namesCount = Enum.GetNames(typeof(MyEnum)).Length;
The number of values defined in MyEnum
(3) can be computed as follows.
var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With