[英]Getting the max value of enum via LINQ and only given the enum type
我知道如何获取枚举的最大值在这里有一个答案: 获取枚举的最大值 。
我的问题是不同的:我需要编写一个仅将枚举Type
作为参数的函数GetMax
,并且我需要获取枚举的最大值。 同时,我的枚举可能来自long
或int
。 为避免溢出,返回的最大值应为数字long
。 这是函数声明:
long GetMax(Type type);
我已经实现了如下功能:
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;
}
我认为可以通过LINQ来实现该功能以简化代码,但是我不知道该怎么做。 我尝试过:
long maxValue = Convert.ToInt64(Enum.GetValues(type).Cast<???>().ToList().Max());
但是我不知道该在Cast <>中填写什么,因为我只知道枚举的类型。
是否有任何解决方案可通过LINQ简化代码? 谢谢!
您可以尝试使用通用方法。
static private T GetMax<T>(Type type)
{
T maxValue = Enum.GetValues(type).Cast<T>().Max();
return maxValue;
}
然后,您只需要传递期望的数据类型即可。
GetMax<long>(typeof(Color))
刚刚意识到, GetValues
返回一个Array
,所以.Select()
不可用,因此您需要在.Cast<Enum>()
之前:
long maxValue = Enum.GetValues(type).Cast<Enum>().Select(x => Convert.ToInt64(x)).Max();
另外,如果您需要实际的枚举值,则可以使用:
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.