5

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.

user2102327
  • 59
  • 2
  • 6
  • 19
  • possible duplicate of https://stackoverflow.com/questions/8560106/isnullorempty-equivalent-for-array-c-sharp – Bhuban Shrestha Jun 07 '17 at 06:48
  • 2
    Leave array out of it if you are going to dynamically scale the collection. If so happens that you already know the length provide that number into List of ctor. – Karolis Kajenas Jun 07 '17 at 06:54

4 Answers4

4
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);
fubo
  • 44,811
  • 17
  • 103
  • 137
1

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.       
  }
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
0

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);
Andre Kraemer
  • 2,633
  • 1
  • 17
  • 28
0

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
Krzysztof Bracha
  • 903
  • 7
  • 19