I have an array, say
int[] array = new int[] { 1, 5, 11, 5 };
How can I check (in the most easy and efficient way) that all elements are positive? If at least one number is not a positive integer, the system will respond in a negative way.
Desired output:
if all the numbers are positive, then it will display "All Positive" else "Wrong"
My shot
int[] array = new int[] { 1, 5, 11, 5 };
var x = array.All(c => c >= '0' && c <= '9');
if (x == true) "Positive" else "Wrong";
You were nearly there before - but you were comparing with characters instead of integers.
If you want to check whether everything is strictly positive, use:
bool allPositive = array.All(x => x > 0);
If you actually want to check they're all non-negative (i.e. 0 is acceptable) use:
bool allNonNegative = array.All(x => x >= 0);
You should definitely consider what you want to do with 0, as your problem statement is actually contradictory. ("All positive" and "no negative" aren't the same thing.)
Note that just like Any
, All
will quit as soon as it knows the result - so if the first value is negative, it won't need to look through the rest.
Use Enumerable.Any like:
if(array.Any(r => r < 0))
{
//Negative number found
}
else
{
//All numbers are positive
}
Or you can use Enumerable.All Like:
if(array.All(r => r > 0))
{
//All numbers are positive
}
else
{
//Negative number found
}
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