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 ?
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();
You could use Any:
bool containsNegative = numArray.Any(i => i < 0)
Or
bool containsNegative = numArray.Min() < 0;
int[] negativeNumbers = numArray.Where(i => i < 0).ToArray();
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