C#, check whether integer array has negative numbers in it
11,068
Solution 1
You could use Any:
bool containsNegative = numArray.Any(i => i < 0)
Or
bool containsNegative = numArray.Min() < 0;
EDIT
int[] negativeNumbers = numArray.Where(i => i < 0).ToArray();
Solution 2
If you're open to using LINQ:
var containsNegatives = numArray.Any(n => n < 0);
Or, if you want to do it the "old fashioned" way...you just have to loop:
var containsNegatives = false;
foreach(var n in numArray)
{
if(n < 0)
{
containsNegatives = true;
break;
}
}
And if you really want to get fancy, you could turn that into an Extension method:
public static class EnumerableExtensions
{
public static bool ContainsNegatives(this IEnumerable<int> numbers)
{
foreach(n in numbers)
{
if(n < 0) return true;
}
return false;
}
}
And call it from your code like:
var containsNegatives = numArray.ContainsNegatives();
Solution 3
var negativeExist = numArray.Any(a => a < 0);
Comments
-
Kuntady Nithesh almost 2 years
I have a array
int[] numArray
. I want to know is there any straight forward way to just check whether array has negative numbers in it ?If there is no direct method even linq will do . I am bit new to linq . Can anyone suggest ?
-
gor over 12 yearsOr you could wrap old fashioned way in Extension method, and use it like LINQ.
-
Justin Niessner over 12 years@gor - Haha...funny that you made the comment while I was adding that to the answer. Good idea.
-
Kuntady Nithesh over 12 yearsHow do i retrieve all negative numbers through linq ?
-
Bala R over 12 yearsthere is no need to loop through all items. You can return when you find the first negative item.
-
Alan over 12 years@IAbstractDownvoteFactory: Any() looks like a better solution than Min(), since Any() returns true upon finding the first negative element, while Min() always loops through the entire array. You might want to indicate this in your answer.
-
Rune FS over 12 years@BalaR which is why the code I've posted exits after finding the first
-
Bala R over 12 yearsAh, I missed the
!res
in the loop contition. Not used to looking conditions like that up there.