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

后端 未结 24 1997
深忆病人
深忆病人 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:26

    Probably a bit overkill, but:

    eRat value = eRat.B;
    eRat nextValue = Enum.GetValues(typeof(eRat)).Cast()
            .SkipWhile(e => e != value).Skip(1).First();
    

    or if you want the first that is numerically bigger:

    eRat nextValue = Enum.GetValues(typeof(eRat)).Cast()
            .First(e => (int)e > (int)value);
    

    or for the next bigger numerically (doing the sort ourselves):

    eRat nextValue = Enum.GetValues(typeof(eRat)).Cast()
            .Where(e => (int)e > (int)value).OrderBy(e => e).First();
    

    Hey, with LINQ as your hammer, the world is full of nails ;-p

提交回复
热议问题