Enum and IEnumerable in C#

本文关键字:in IEnumerable and Enum | 更新日期: 2023-09-27 18:16:34

my TIME Enum包含Annual、Monthly、weekly、daily和hour。

这里我想决定哪个是最小值并返回它

我该怎么做?这是我试过的代码。

private Time DecideMinTime(IEnumerable<Time> g)
{
    var minTime = Time.Hourly;
    foreach (var element in g)
    {
        minTime = element;
    }
    return minTime;
}   

Enum and IEnumerable in C#

假设枚举元素的数值决定最小值:

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;
        }
    }
}

为方便起见,可以将整型值赋给enum:

enum Time : byte {Hourly=1, Daily=2, Weekly=3, Monthly=4, Annual=5};

private static Time DecideMinTime(IEnumerable<Time> g)
{            
   return g.Min();                        
}