Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, check whether integer array has negative numbers in it

Tags:

arrays

c#

linq

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 ?

like image 689
Kuntady Nithesh Avatar asked Sep 12 '26 08:09

Kuntady Nithesh


2 Answers

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();
like image 139
Justin Niessner Avatar answered Sep 13 '26 22:09

Justin Niessner


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();
like image 31
Joe Avatar answered Sep 13 '26 21:09

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!