Loading ...

Find Maximum value from an Enum | CodeAsp.Net

Find Maximum value from an Enum

 /5
0 (0votes)

    Here I have discussed find the maximum value from enum.
    Suppose we have an enum like:

public enum TestEnum

    {

        A=1,

        X=2,

        E=3,

        R=4,

        O=5

    }
    if our enum have values like above(Incremented by one),then we can Find the Max enum values like as follows:

  String strMaxEnumValue = Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Last().ToString();

    It returns last element of the sequence.

    It gives you "O" as result.

  int maxEnumValue = Convert.ToInt32(Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Last());

    Above line of code returns the value of "O" i.e. 5.

    Now this Code is not working if our enum is not have values in a sequence i.e our enum have generic sequence like:

public enum TestEnum

    {

        A=4,

        X=6,

        E=10,

        R=2,

        O=1

    }
    In this case above code always gives you last value of enum i.e. "O".
    Now to find out the Maximum value of Enum then We achive this as follows.

  String strMaxEnumValue = Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Max().ToString();

   It returns Maximum value from the generic sequence,i.e. the result will be "E".

 int MaxEnumValue = Convert.ToInt32(Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Max());

   The result of the avobe line of code is "10";

   The Generic Solution to find out the Maximum value from enum is :

 String strMaxEnumValue = Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Max().ToString();

    OR

 int MaxEnumValue = Convert.ToInt32(Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Max());
Thanks.

Comments (2)

   
mohit
Thank you.It's very helpful
11/29/2009
 · 
by
   
shaitender
i guess there is prob in editor .. it is showing text in the blogentry " "
11/30/2009
 · 
by
  • :*
  • :*
  • :
 *

Top Posts