Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all the elements in an array are positive integers?

Tags:

c#

linq

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";
like image 252
priyanka.sarkar Avatar asked May 09 '13 05:05

priyanka.sarkar


2 Answers

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.

like image 135
Jon Skeet Avatar answered Sep 20 '22 02:09

Jon Skeet


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
}
like image 33
Habib Avatar answered Sep 19 '22 02:09

Habib