0

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!

Caesium
  • 789
  • 3
  • 7
  • 24

3 Answers3

1

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

D-Shih
  • 44,943
  • 6
  • 31
  • 51
1

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();
vasily.sib
  • 3,871
  • 2
  • 23
  • 26
  • Yes, we must use `.Cast()` to convert `Array` to `IEnumerable` so that `.Select` can work. So the main point of this question is if we don't know `YOUR ENUM`, how can we cast it? So far we know that we can cast it into `Enum` and `object`. – Caesium Nov 09 '18 at 03:52
  • @Caesium actualy, instead of `.Cast()` you may use `.OfType()`. Difference here, in case of `.OfType()`, is that if one element of `Array` will be not of type `T` it will be skipped. `.Cast()` in such situation will throw `CastException`. – vasily.sib Nov 09 '18 at 06:37
1

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

return Convert.ToInt64(Enum.GetValues(type).Cast<object>().Max());
Caesium
  • 789
  • 3
  • 7
  • 24