How to handle double.NaN for a generic method accepting IComparable in C #

I have a general GetMinimum method. It takes an array of type IComparable (so it can 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 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; } 
+4
source share
3 answers

Since both NaN < x and NaN > x will always be false, the query for the minimum set that can contain NaN is simply undefined. It's like dividing by zero: there is no valid answer.

Thus, the logical approach would be to pre-filter the values. It will not be common, but it should be good.

  var results = inputArray.EliminateNaN().GetMinimum(); 

Separation of problems: filtering should not be the responsibility (and load) of GetMinimum() .

+4
source

You cannot inside the method. The reason is that you do not know that T can be from within the method. Maybe you can do a little work, but ideally this should be your approach:

 public T GetMinimum<T>(T[] array, params T[] ignorables) where T : IComparable<T> { T result = array[0]; //some issue with the logic here.. what if array is empty foreach (T item in array) { if (ignorables.Contains(item) continue; if (result.CompareTo(item) > 0) { result = item; } } return result; } 

Now call it:

 double[] inputArray = { double.NaN, double.NegativeInfinity, -2.3, 3 }; GetMinimum(inputArray, double.NaN); 

If you are sure that only the element is ignored, then you can take only T as the second parameter (possibly as an optional parameter).

Or else in a shorter approach, simply:

 inputArray.Where(x => !x.Equals(double.NaN)).Min(); 
+1
source

In accordance with this Q & A, it was complicated: Sorting an array of paired discharges with NaN in it

Fortunately, you can hack it:

 if( item is Single || item is Double ) { Double fitem = (Double)item; if( fitem == Double.NaN ) continue; } 
-1
source

All Articles