我的TIME Enum包含年度,每月,每周,每日和每小时。
在这里,我想确定哪个是最小值,并希望返回。
我该怎么做?这是我试过的代码。
private Time DecideMinTime(IEnumerable<Time> g)
{
var minTime = Time.Hourly;
foreach (var element in g)
{
minTime = element;
}
return minTime;
}
答案 0 :(得分:7)
假设enum元素的数值决定了最小值:
private Time DecideMinTime(IEnumerable<Time> g)
{
if (g == null) { throw new ArgumentNullException("g"); }
return (Time)g.Cast<int>().Min();
}
如果数字值表示相反的顺序,那么您将使用.Max()
而不是.Min()
。
如图所示,数字顺序不一致。这可以通过使用指示正确顺序的映射来解决:
static class TimeOrdering
{
private static readonly Dictionary<Time, int> timeOrderingMap;
static TimeOrdering()
{
timeOrderingMap = new Dictionary<Time, int>();
timeOrderingMap[Time.Hourly] = 1;
timeOrderingMap[Time.Daily] = 2;
timeOrderingMap[Time.Weekly] = 3;
timeOrderingMap[Time.Monthly] = 4;
timeOrderingMap[Time.Annual] = 5;
}
public Time DecideMinTime(IEnumerable<Time> g)
{
if (g == null) { throw new ArgumentNullException("g"); }
return g.MinBy(i => timeOrderingMap[i]);
}
public TSource MinBy<TSource, int>(
this IEnumerable<TSource> self,
Func<TSource, int> ordering)
{
if (self == null) { throw new ArgumentNullException("self"); }
if (ordering == null) { throw new ArgumentNullException("ordering"); }
using (var e = self.GetEnumerator()) {
if (!e.MoveNext()) {
throw new ArgumentException("Sequence is empty.", "self");
}
var minElement = e.Current;
var minOrder = ordering(minElement);
while (e.MoveNext()) {
var curOrder = ordering(e.Current);
if (curOrder < minOrder) {
minOrder = curOrder;
minElement = e.Current;
}
}
return minElement;
}
}
}
答案 1 :(得分:2)
为了方便起见,您可以为枚举值分配int值:
enum Time : byte {Hourly=1, Daily=2, Weekly=3, Monthly=4, Annual=5};
然后
private static Time DecideMinTime(IEnumerable<Time> g)
{
return g.Min();
}
这样你就可以避免来回摆动。