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!