Total number of items defined in an enum

前端 未结 10 697
你的背包
你的背包 2020-11-30 18:36

How can I get the number of items defined in an enum?

相关标签:
10条回答
  • 2020-11-30 19:15

    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();
    
    0 讨论(0)
  • 2020-11-30 19:15

    For Visual Basic:

    [Enum].GetNames(typeof(MyEnum)).Length did not work with me, but [Enum].GetNames(GetType(Animal_Type)).length did.

    0 讨论(0)
  • 2020-11-30 19:16

    From the previous answers just adding code sample.

     class Program
        {
            static void Main(string[] args)
            {
                int enumlen = Enum.GetNames(typeof(myenum)).Length;
                Console.Write(enumlen);
                Console.Read();
            }
            public enum myenum
            {
                value1,
                value2
            }
        }
    
    0 讨论(0)
  • 2020-11-30 19:20

    I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:

    var namesCount = (int)MyEnum.Length;
    

    Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.

    0 讨论(0)
  • 2020-11-30 19:22

    I've run a benchmark today and came up with interesting result. Among these three:

    var count1 = typeof(TestEnum).GetFields().Length;
    var count2 = Enum.GetNames(typeof(TestEnum)).Length;
    var count3 = Enum.GetValues(typeof(TestEnum)).Length;
    

    GetNames(enum) is by far the fastest!

    |         Method |      Mean |    Error |   StdDev |
    |--------------- |---------- |--------- |--------- |
    | DeclaredFields |  94.12 ns | 0.878 ns | 0.778 ns |
    |       GetNames |  47.15 ns | 0.554 ns | 0.491 ns |
    |      GetValues | 671.30 ns | 5.667 ns | 4.732 ns |
    
    0 讨论(0)
  • 2020-11-30 19:23

    Enum.GetValues(typeof(MyEnum)).Length;

    0 讨论(0)
提交回复
热议问题