Is there any quick way of turning all the members of an array into absolute and find the max number among them? For example in this array:
-100 25 43
The max is 43, but I want to get 100 from my code. Is there's any simple/fast method that I can use to find max regardless of its sign? or do I have to use a for loop to turn all the array members into absolute and then find the max among them?
Try this:
int[] array = {-100, 25, 43};
int max = array.Select(Math.Abs).Max();
This works:
var numbers = new[] { -100, 25, 43 };
var absoluteMax = numbers.Select(x => Math.Abs(x)).Max();
I get 100
as requested.
Do be careful if one of your numbers is int.MinValue
then you get an OverflowException
- "Negating the minimum value of a twos complement number is invalid."
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