简体   繁体   中英

Enum and IEnumerable in C#

my TIME Enum contains Annual, Monthly, weekly, daily and Hourly.

Here I want to decide which is the minimum and want to return that.

How can I do this ? Here is the code I tried.

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

Assuming that the numeric value of the enum elements decides what the minimum is:

private Time DecideMinTime(IEnumerable<Time> g)
{
    if (g == null) { throw new ArgumentNullException("g"); }

    return (Time)g.Cast<int>().Min();
}

If the numeric values indicate the opposite order then you would use .Max() instead of .Min() .


As indicated, the numeric order is not consistent. This can be worked around simply by using a mapping indicating the correct order:

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

To make it easier you can assign int values to your enum:

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

and then

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

That way you avoid casting back and forth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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