I have a List<double> MyList something looking like this: 4.75/1.01/5.66/NaN/42.42/3.33
I’d like to get the minimum value of 1.01 out of it, but I get d = NaN when doing double d = MyList.Min(); Tried, after some long internet strolls, something with LINQ to no avail.
Some LINQ afictionados around here, who can help me out?
As always, my gratitude will be immense.

Dani AI

Generated

Short answer and why it happened: 's suggestion to skip special values is correct. LINQ's implementation of Enumerable.Min treats NaN specially — the Min code intentionally updates the running minimum when it sees a NaN, so a single NaN in the sequence will cause the final result to be NaN. The LINQ source shows this behavior in the Min implementations for float/double. (Enumerable.cs source). (dotnetframework.org)

Practical options (pick one that fits your workflow):

  • Fix at parse time: when you scrape the table, map empty cells to null (use double?) instead of inserting double.NaN. That makes "missing" explicit and lets Min() over IEnumerable<double?> return null if there are no real numbers.
  • Quick filter: exclude non-finite values (NaN and infinities) before calling Min — this is what recommended, and it is fine for ad-hoc stats.
  • Single-pass safe min: for repeated/statistics work prefer a one-pass routine that ignores NaN/Infinity and returns a nullable result; it avoids surprises and is efficient:
public static double? MinFinite(this IEnumerable<double> seq)
{
    double? min = null;
    foreach (var v in seq)
    {
        if (double.IsNaN(v) || double.IsInfinity(v)) continue;
        if (!min.HasValue || v < min.Value) min = v;
    }
    return min;
}

Implementation notes and gotchas: if you filter everything out and call the non-nullable Min() overload you will get an exception (no elements), so either use nullable types, check .Any() first, or use a safe helper like above. Also be mindful of Infinity values (they can skew min/max) — treat them explicitly if they may appear in your scraped data. (dotnetframework.org)

Recommended Answers

All 3 Replies

The first thing that comes to mind is to filter out the special value(s): MyList.Where(x => !double.IsNaN(x)).Min().

Though depending on what might be acceptable insertions into the list, you might need to consider things like NegativeInfinity as well.

commented: kudos! +15

Thanks! Problem solved!

To clarify the NegativeInfinity issue a bit. I harvested(scrape is such an ugly word) a table from a website. One column (which I'm interested in) had some real strings and some empty cells. I changed the empty cells to NaN. So no NegativeInfinity issue here. I'd just like to do some statistics on my list. Don't no if this is the right way to go, perhaps I better remove the NaN cells...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.