Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from list the double value that has the highest absolute value, without making the return value absolute

Tags:

c#

math

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
like image 806
Wobbles Avatar asked Nov 07 '25 21:11

Wobbles


1 Answers

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));
like image 64
mjwills Avatar answered Nov 10 '25 11:11

mjwills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!