'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.
Solution 1:[1]
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);
Solution 2:[2]
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.
}
Solution 3:[3]
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);
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Andre Kraemer |
| Solution 4 |
