user2102327
user2102327

Reputation: 109

How can I check wether an array contains any item or is completely empty?

If I define an integer array:

int[] a = new int[13];

and I do not insert any item into it, how can I know whether the array a contains any items or is completely empty? Do I have to iterate through all the a.Length indices? In a list

List<int> b = new List<int>();

if I check:

if(b.Count == 0)
{
    // The list does not contain any items.
}

Is there an equivalent way to check an array? I found on the internet the check if an array is null or empty. In my case I know for sure that the array is not null. I just wish to know whether it contains any item or not. I do not care in which position within the array and also not exactly which item. Thank you very much in advance.

Upvotes: 5

Views: 19485

Answers (4)

fubo
fubo

Reputation: 45947

int[] a = new int[13]; // [0,0,0,0,0,0,0,0,0,0,0,0,0]

allocates a array with 13 items. The value of each item is 0 or default(int).

So you have to check

bool isEmpty =  a.All(x => x == default(int));

If 0 is a valid value within your array, you should use nullable type:

int?[] a = new int?[13]; // [null,null,null,null,null,null,null,null,null,null,null,null,null]
bool isEmpty =  a.All(x => !x.HasValue);

Upvotes: 4

Krzysztof Bracha
Krzysztof Bracha

Reputation: 913

You can create your own class which encapsulates the Array class and keeps track of whether the array has been changed yet or not.

public class MyArray<T>
{
    private T[] array;
    private bool altered = false;

    public MyArray(int size)
    {
        array= new T[size + 1];
    }

    public T this[int index]
    {
        get
        {
            return array[index];
        }
        set
        {
            altered = true;
            array[index] = value;
        }

    }

    public bool HasBeenAltered()
    {
        return altered;
    }
}

The function HasBeenAltered() tells whether any item of the array has been updated.

MyArray<int> arr = new MyArray<int>(10);
arr.HasBeenAltered(); // false

arr[4] = 4;
arr.HasBeenAltered(); // true

Upvotes: 0

Willy David Jr
Willy David Jr

Reputation: 9131

Since its an integer, you can check if all values are zero:

if (array.All(y=>y == 0))
  {
    //If all values are zero, this will proceed on this statement.       
  }

Upvotes: 1

Andre Kraemer
Andre Kraemer

Reputation: 2761

When you define an array like this:

int[] a = new int[13];

you get an array that contains 13 elements. All of them have the value zero because that's the default value for an int.

So what you could do is:

bool hasElements = a.Any(x => x != 0);

Upvotes: 0

Related Questions