Search code examples
c#.netc++-cli

Determine if array contains all zeroes


I create the following array like this:

array<UInt16>^ temp = gcnew array<UInt16>(1000);

How do I determine if this entire array has been filled with zero or not.

I think I may be able to use TrueForAll(T) but I'm not sure.


Solution

  • This should work properly (here I used LINQ):

    IEnumerable<int> values = new List<int>(); // Or use any array type instead of List.
    
    ... Add your values here ...
    
    var allAreZero = !values.Any(v => v != 0);
    

    P.S. the array class inherits IEnumerable.

    And here is a solution with foreach:

    var isAllZero = true;
    foreach (var value in values)
    {
        if (value != 0)
        {
            isAllZero = false;
            break;
        }
    }
    

    UPDATE

    The really difference between TrueForAll, and my LINQ code is: LINQ code uses the fluent (or maybe also query) syntax, where TrueForAll is just a normal function where you send the array as a parameter.