Equivalent of Math.Min & Math.Max for Dates?

后端 未结 9 1920
渐次进展
渐次进展 2020-12-13 05:16

What\'s the quickest and easiest way to get the Min (or Max) value between two dates? Is there an equivalent to Math.Min (& Math.Max) for dates?

I want to do som

9条回答
  •  佛祖请我去吃肉
    2020-12-13 05:41

    How about:

    public static T Min(params T[] values)
    {
        if (values == null) throw new ArgumentNullException("values");
        var comparer = Comparer.Default;
        switch(values.Length) {
            case 0: throw new ArgumentException();
            case 1: return values[0];
            case 2: return comparer.Compare(values[0],values[1]) < 0
                   ? values[0] : values[1];
            default:
                T best = values[0];
                for (int i = 1; i < values.Length; i++)
                {
                    if (comparer.Compare(values[i], best) < 0)
                    {
                        best = values[i];
                    }
                }
                return best;
        }        
    }
    // overload for the common "2" case...
    public static T Min(T x, T y)
    {
        return Comparer.Default.Compare(x, y) < 0 ? x : y;
    }
    

    Works with any type that supports IComparable or IComparable.

    Actually, with LINQ, another alternative is:

    var min = new[] {x,y,z}.Min();
    

提交回复
热议问题