How to get next (or previous) enum value in C#

后端 未结 24 1900
深忆病人
深忆病人 2020-12-04 10:59

I have an enum which is defined like this:

public enum eRat { A = 0, B=3, C=5, D=8 };

So given value eRat.B, I want to get the

相关标签:
24条回答
  • 2020-12-04 11:13

    Hope this part of my code helps you:

    public enum EGroupedBy
    {
        Type,
        InterfaceAndType,
        Alpha,
        _max
    }
    
    private void _btnViewUnit_Click(object sender, EventArgs e)
    {
        int i = (int)GroupedBy;
    
        i = (i + 1) % (int)EGroupedBy._max;
    
        GroupedBy = (EGroupedBy) i;
    
        RefreshUnit();
    }
    
    0 讨论(0)
  • 2020-12-04 11:13

    I tried the first solution but it did not work for me. Below is my solution:

        public  object NextEnumItem(object currentEnumItem) 
        {
            if (!currentEnumItem.GetType().IsEnum) throw new 
                    ArgumentException(String.Format("Argument is not an Enum"));
            Array Arr = Enum.GetValues(currentEnumItem.GetType());
            int j = Array.IndexOf(Arr,currentEnumItem) + 1;
            return (Arr.Length == j) ? currentEnumItem : Arr.GetValue(j);
        }
    
        public object PreviousEnumItem(object currentEnumItem)
        {
            if (!currentEnumItem.GetType().IsEnum)
                throw new ArgumentException(String.Format("Argument is not an Enum"));
            Array Arr = Enum.GetValues(currentEnumItem.GetType());
            int j = Array.IndexOf(Arr, currentEnumItem) - 1;
            return (j==-1) ? currentEnumItem : Arr.GetValue(j);
        }
    
    0 讨论(0)
  • 2020-12-04 11:14

    From comments I had many question like: "Why would you ever want to use enum in this way." Since so many of you asked, let me give you my use case and see if you agree then:

    I have a fixed array of items int[n]. Depending on the situation I want to enumerate through this array differently. So i defined:

    int[] Arr= {1,2,34,5,6,78,9,90,30};
    enum eRat1 { A = 0, B=3, C=5, D=8 }; 
    enum eRat2 { A, AA,AAA,B,BB,C,C,CC,D }; 
    
    void walk(Type enumType) 
    { 
       foreach (Type t in Enum.GetValues(enumType)) 
       { 
          write(t.ToString() + " = " + Arr[(int)t)]; 
       }
    } 
    

    and call walk(typeof(eRAt1)) or walk(typeof(eRAt2))

    then i get required output

    1) walk(typeof(eRAt1))

    A = 1
    B = 5
    C = 78
    D = 30
    

    2) walk(typeof(eRAt2))

    A = 1
    AA = 2
    AAA = 34
    B = 5
    BB = 6
    C = 78
    CC = 90
    D = 30
    

    This is very simplified. But i hope, this explains. There are some other advantages to this, as having enum.toString(). So basically i use enums as indexers.

    So using the solution I can do something like this now.

    In sequence eRat1 next value to B is C, but in eRat2 it is BB. So depending on which sequence I am interested in, I can do e.next and depending on enumType I will either get C or BB. How would one achieve that with dictionaries?

    I think this a rather elegant use of enums.

    0 讨论(0)
  • 2020-12-04 11:14

    I'm using this here:

    public MyEnum getNext() {
        return this.ordinal() < MyEnum.values().length - 1 ? 
                                MyEnum.values()[this.ordinal() + 1] : 
                                MyEnum.values()[0];
    }
    
    0 讨论(0)
  • 2020-12-04 11:16

    LINQ solution that does not break on last element but continues at the default again:

    var nextValue = Enum.GetValues(typeof(EnumT)).Cast<EnumT>().Concat(new[]{default(EnumT)}).SkipWhile(_ => _ != value).Skip(1).First();
    
    0 讨论(0)
  • 2020-12-04 11:20

    Works up to "C" since there is no answer on what to return after "D".

    [update1]: Updated according to Marc Gravell's suggestion.

    [update2]: Updated according to how husayt's wanted - return "A" for the next value of "D".

    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Next enum of A = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.A));
            Console.WriteLine("Next enum of B = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.B));
            Console.WriteLine("Next enum of C = {0}", eRatEnumHelper.GetNextEnumValueOf(eRat.C));
        }
    }
    
    public enum eRat { A = 0, B = 3, C = 5, D = 8 };
    
    public class eRatEnumHelper
    {
        public static eRat GetNextEnumValueOf(eRat value)
        {
            return (from eRat val in Enum.GetValues(typeof (eRat)) 
                    where val > value 
                    orderby val 
                    select val).DefaultIfEmpty().First();
        }
    }
    

    Result

    Next enum of A = B
    Next enum of B = C
    Next enum of C = D
    Next enum of D = A

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