Caesium
Caesium

Reputation: 1009

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!

Upvotes: 0

Views: 732

Answers (3)

Caesium
Caesium

Reputation: 1009

I found out a method, we can cast the enum into object:

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

Upvotes: 1

vasily.sib
vasily.sib

Reputation: 4002

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();

Upvotes: 1

D-Shih
D-Shih

Reputation: 46239

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

Upvotes: 1

Related Questions