Getting the max value of an enum

后端 未结 11 2286
旧时难觅i
旧时难觅i 2020-12-07 13:42

How do you get the max value of an enum?

相关标签:
11条回答
  • 2020-12-07 13:57

    It is not usable in all circumstances, but I often define the max value myself:

    enum Values {
      one,
      two,
      tree,
      End,
    }
    
    for (Values i = 0; i < Values.End; i++) {
      Console.WriteLine(i);
    }
    
    var random = new Random();
    Console.WriteLine(random.Next((int)Values.End));
    

    Of course this won't work when you use custom values in an enum, but often it can be an easy solution.

    0 讨论(0)
  • 2020-12-07 14:01

    In F#, with a helper function to convert the enum to a sequence:

    type Foo =
        | Fizz  = 3
        | Bang  = 2
    
    // Helper function to convert enum to a sequence. This is also useful for iterating.
    // stackoverflow.com/questions/972307/can-you-loop-through-all-enum-values-c
    let ToSeq (a : 'A when 'A : enum<'B>) =
        Enum.GetValues(typeof<'A>).Cast<'B>()
    
    // Get the max of Foo
    let FooMax = ToSeq (Foo()) |> Seq.max   
    

    Running it...

    > type Foo = | Fizz = 3 | Bang = 2
    > val ToSeq : 'A -> seq<'B> when 'A : enum<'B>
    > val FooMax : Foo = Fizz
    

    The when 'A : enum<'B> is not required by the compiler for the definition, but is required for any use of ToSeq, even by a valid enum type.

    0 讨论(0)
  • 2020-12-07 14:02

    According to Matt Hamilton's answer, I thought on creating an Extension method for it.

    Since ValueType is not accepted as a generic type parameter constraint, I didn't find a better way to restrict T to Enum but the following.

    Any ideas would be really appreciated.

    PS. please ignore my VB implicitness, I love using VB in this way, that's the strength of VB and that's why I love VB.

    Howeva, here it is:

    C#:

    static void Main(string[] args)
    {
        MyEnum x = GetMaxValue<MyEnum>(); //In newer versions of C# (7.3+)
        MyEnum y = GetMaxValueOld<MyEnum>();  
    }
    
    public static TEnum GetMaxValue<TEnum>()
      where TEnum : Enum
    {
         return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Max();
    }
    
    //When C# version is smaller than 7.3, use this:
    public static TEnum GetMaxValueOld<TEnum>()
      where TEnum : IComparable, IConvertible, IFormattable
    {
        Type type = typeof(TEnum);
    
        if (!type.IsSubclassOf(typeof(Enum)))
            throw new
                InvalidCastException
                    ("Cannot cast '" + type.FullName + "' to System.Enum.");
    
        return (TEnum)Enum.ToObject(type, Enum.GetValues(type).Cast<int>().Last());
    }
    
    
    
    enum MyEnum
    {
        ValueOne,
        ValueTwo
    }
    

    VB:

    Public Function GetMaxValue _
        (Of TEnum As {IComparable, IConvertible, IFormattable})() As TEnum
    
        Dim type = GetType(TEnum)
    
        If Not type.IsSubclassOf(GetType([Enum])) Then _
            Throw New InvalidCastException _
                ("Cannot cast '" & type.FullName & "' to System.Enum.")
    
        Return [Enum].ToObject(type, [Enum].GetValues(type) _
                            .Cast(Of Integer).Last)
    End Function
    
    0 讨论(0)
  • 2020-12-07 14:02

    After tried another time, I got this extension method:

    public static class EnumExtension
    {
        public static int Max(this Enum enumType)
        {           
            return Enum.GetValues(enumType.GetType()).Cast<int>().Max();             
        }
    }
    
    class Program
    {
        enum enum1 { one, two, second, third };
        enum enum2 { s1 = 10, s2 = 8, s3, s4 };
        enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };
    
        static void Main(string[] args)
        {
            Console.WriteLine(enum1.one.Max());        
        }
    }
    
    0 讨论(0)
  • 2020-12-07 14:02

    Use the Last function could not get the max value. Use the "max" function could. Like:

     class Program
        {
            enum enum1 { one, two, second, third };
            enum enum2 { s1 = 10, s2 = 8, s3, s4 };
            enum enum3 { f1 = -1, f2 = 3, f3 = -3, f4 };
    
            static void Main(string[] args)
            {
                TestMaxEnumValue(typeof(enum1));
                TestMaxEnumValue(typeof(enum2));
                TestMaxEnumValue(typeof(enum3));
            }
    
            static void TestMaxEnumValue(Type enumType)
            {
                Enum.GetValues(enumType).Cast<Int32>().ToList().ForEach(item =>
                    Console.WriteLine(item.ToString()));
    
                int maxValue = Enum.GetValues(enumType).Cast<int>().Max();     
                Console.WriteLine("The max value of {0} is {1}", enumType.Name, maxValue);
            }
        }
    
    0 讨论(0)
  • 2020-12-07 14:03

    I agree with Matt's answer. If you need just min and max int values, then you can do it as follows.

    Maximum:

    Enum.GetValues(typeof(Foo)).Cast<int>().Max();
    

    Minimum:

    Enum.GetValues(typeof(Foo)).Cast<int>().Min();
    
    0 讨论(0)
提交回复
热议问题