Search code examples
c#.net.net-4.6.1

C# DataTable Min Value excluding NaN


I am having a problem with datatable in C#. I want to find the min value for a column in a datatable that has NaN value. For example:

c1  c2  c3
1   2   3
4   NaN NaN
NaN 7   9

Say if I want to find the min value in c1, I would do:

int minValue = Convert.ToInt32(dt.Compute("min([c1])", string.Empty));

or:

int minValue = dt.AsEnumerable().Min(r => r.Field<int>("c1"));

I am expecting both of them to return an integer value (in this case: 1) However both of them instead returns

NaN

I am using .NET 4.6.1. Is there a way to tell the datatable to exclude NaN value when computing min value? (Surprisingly no one seems to be having similar question when I am searching this up.)


Solution

  • Use Linq's Where and Min functions:

    double FindColumnMinValue(IEnumerable<double> columnValues) => columnValues.Where(c => !double.IsNaN(c)).Min();