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

后端 未结 24 1991
深忆病人
深忆病人 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条回答
  •  猫巷女王i
    2020-12-04 11:25

    Seems like an abuse of the enum class to me - but this would do it (assuming that calling Next on the last value would cause wrap-around):

    public static eRat Next(this eRat target)
    {
        var nextValueQuery = Enum.GetValues(typeof(eRat)).Cast().SkipWhile(e => e != target).Skip(1);
        if (nextValueQuery.Count() != 0)
        {
            return (eRat)nextValueQuery.First();
        }
        else
        {
            return eRat.A;
        }
    }
    

    And this would give you the previous value on the same basis:

    public static eRat Previous(this eRat target)
    {
        var nextValueQuery = Enum.GetValues(typeof(eRat)).Cast().Reverse().SkipWhile(e => e != target).Skip(1);
        if (nextValueQuery.Count() != 0)
        {
            return (eRat)nextValueQuery.First();
        }
        else
        {
            return eRat.D;
        }
    }
    

提交回复
热议问题