Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?
double[] vals = new double[] { 2.3, 1.7, -3.8};
vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8
One approach to consider:
var max = vals
.OrderByDescending(z => Math.Abs(z))
.FirstOrDefault();
Alternatively, consider using MoreLinq's MaxBy. It is faster than both my and Samvel's solution, especially for larger sets of inputs.
var max = vals.MaxBy(z => Math.Abs(z));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With