[英]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.