简体   繁体   中英

Getting the max value of enum via LINQ and only given the enum type

I know the how to get the max value of a enum has an answer here: Getting the max value of an enum .

My question is different: I need to write a function GetMax which only takes the Type of the enum as parameter, and I need to get the max value of the enum. Meanwhile, my enum may derive from long or int . To avoid overflow, the max value returned should be numerical long . Here is the function declaration:

long GetMax(Type type);

I have implemented the function like below:

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;
}

I think the function can be implemented via LINQ to simplified the code, but I don't know how to do that. I tried like:

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

But I don't know what to fill in the Cast<> , because I only know the type of the enum.

Is there any solution to simplify the code via LINQ? Thx!

You can try to use a generic method.

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

Then you just need to pass your expect data type.

GetMax<long>(typeof(Color))

c# online

Just realise, that GetValues return an Array , so .Select() is not available, so you need to .Cast<Enum>() before:

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

Also, if you need a an actual enum value, you may use:

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

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

return Convert.ToInt64(Enum.GetValues(type).Cast<object>().Max());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM