I have a generic GetMinimum
method. It accepts array of IComparable type (so it may be string[]
or double[]
). in the case of double[]
how can I implement this method to ignore the double.NaN
values? (I'm looking for good practices)
when I pass this array
double[] inputArray = { double.NaN, double.NegativeInfinity, -2.3, 3 };
it returns the double.NaN!
public T GetMinimum<T>(T[] array) where T : IComparable<T>
{
T result = array[0];
foreach (T item in array)
{
if (result.CompareTo(item) > 0)
{
result = item;
}
}
return result;
}
Since both NaN < x
and NaN > x
will always be false, asking for the minimum of a collection that can contain NaN
is simply not defined. It is like dividing by zero: there is no valid answer.
So the logical approach would be to pre-filter the values. That will not be generic but that should be OK.
var results = inputArray.EliminateNaN().GetMinimum();
Separation of concerns: the filtering should not be the responsibility (and burden) of GetMinimum()
.