Equivalent of Math.Min & Math.Max for Dates?
There's no built in method to do that. You can use the expression:
(date1 > date2 ? date1 : date2)
to find the maximum of the two.
You can write a generic method to calculate Min
or Max
for any type (provided that Comparer<T>.Default
is set appropriately):
public static T Max<T>(T first, T second) {
if (Comparer<T>.Default.Compare(first, second) > 0)
return first;
return second;
}
You can use LINQ too:
new[]{date1, date2, date3}.Max()
There is no overload for DateTime values, but you can get the long value Ticks
that is what the values contain, compare them and then create a new DateTime value from the result:
new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))
(Note that the DateTime structure also contains a Kind
property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)
How about:
public static T Min<T>(params T[] values)
{
if (values == null) throw new ArgumentNullException("values");
var comparer = Comparer<T>.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>(T x, T y)
{
return Comparer<T>.Default.Compare(x, y) < 0 ? x : y;
}
Works with any type that supports IComparable<T>
or IComparable
.
Actually, with LINQ, another alternative is:
var min = new[] {x,y,z}.Min();