通过LINQ获取枚举的最大值,并且仅给出枚举类型

时间:2018-11-09 03:02:50

标签: c# linq enums runtime

我知道如何获取枚举的最大值,这里有一个答案:Getting the max value of an enum

我的问题不同:我需要编写一个函数GetMax,该函数仅将枚举的Type作为参数,并且需要获取枚举的最大值。同时,我的枚举可能来自longint。为避免溢出,返回的最大值应为数字long。 这是函数声明:

long GetMax(Type type);

我已经实现了如下功能:

static private long GetMax(Type type)
{
    long maxValue = 0;
    if (Enum.GetValues(type).Length != 0)
    {
        maxValue = Int64.MinValue;
        foreach (var x in Enum.GetValues(type))
        {
            maxValue = Math.Max(maxValue, Convert.ToInt64(x));
        }
    }
    return maxValue;
}

我认为可以通过LINQ来实现该功能以简化代码,但是我不知道该怎么做。我尝试过:

long maxValue = Convert.ToInt64(Enum.GetValues(type).Cast<???>().ToList().Max());

但是我不知道在 Cast <> 中填写什么,因为我只知道枚举的类型。

是否有解决方案可通过LINQ简化代码?谢谢!

3 个答案:

答案 0 :(得分:1)

您可以尝试使用通用方法。

static private T GetMax<T>(Type type)
{
    T maxValue = Enum.GetValues(type).Cast<T>().Max();
    return maxValue;
}

然后,您只需要传递期望的数据类型。

GetMax<long>(typeof(Color))

c# online

答案 1 :(得分:1)

只需意识到GetValues返回一个Array,所以.Select()不可用,因此您需要在.Cast<Enum>()之前:

long maxValue = Enum.GetValues(type).Cast<Enum>().Select(x => Convert.ToInt64(x)).Max();

此外,如果您需要实际的枚举值,则可以使用:

var maxValue = Enum.GetValues(type).Cast<Enum>().Max();

答案 2 :(得分:1)

我找到了一种方法,我们可以将枚举转换为object

return Convert.ToInt64(Enum.GetValues(type).Cast<object>().Max());
相关问题