简体   繁体   English

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

[英]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. 我的问题是不同的:我需要编写一个仅将枚举Type作为参数的函数GetMax ,并且我需要获取枚举的最大值。 Meanwhile, my enum may derive from long or int . 同时,我的枚举可能来自longint To avoid overflow, the max value returned should be numerical long . 为避免溢出,返回的最大值应为数字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. 我认为可以通过LINQ来实现该功能以简化代码,但是我不知道该怎么做。 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. 但是我不知道该在Cast <>中填写什么,因为我只知道枚举的类型。

Is there any solution to simplify the code via LINQ? 是否有任何解决方案可通过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 C#在线

Just realise, that GetValues return an Array , so .Select() is not available, so you need to .Cast<Enum>() before: 刚刚意识到, GetValues返回一个Array ,所以.Select()不可用,因此您需要在.Cast<Enum>()之前:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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