Masoud Darvishian
Masoud Darvishian

Reputation: 3964

Detecting an empty array without looping

How can i find out an array is empty or not, without looping?!
is there any method or anything else?

I mean, in some code like this:

string[] names = new string[5];
names[0] = "Scott";
names[1] = "jack";
names[2] = null;
names[3] = "Jones";
names[4] = "Mesut";

// or

int[] nums = new int[4];
nums[0] = 1;
// nums[1] = 2;
nums[2] = 3;
nums[3] = 4;

or some code like this:

using System;
class Example
{
    static void Main()
    {
        int size = 10;
        int counter;
        string[] str = new string[size];

        for (counter = 0; counter < size; counter++)
        {
            str[counter] = "A" + counter;
        }

        str[3] = null;

        if (counter == size)
            Console.WriteLine("Our array is full!");
        if(counter < size)
            Console.WriteLine("Our array is not full");

        for (int i = 0; i < size; i++)
        {
            Console.WriteLine(str[i]);
        }
    }
}

is there anything else for detecting an empty array without looping?

Upvotes: 0

Views: 520

Answers (3)

Avishek
Avishek

Reputation: 1896

There is no other way than looping through, even LINQ also does the looping automatically. Instead, use a list<> and check if (listName!=null && listName.Length!=0)

Hope it helps :)

Upvotes: 2

VoidMain
VoidMain

Reputation: 2047

You can use LINQ for that, to check if any element is empty in the array you just can do:

var hasNulls = myArray.Any( a => a == null );

Or if you want to select the ones with values:

var notNulls = myArray.Where( a => a != null );

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

An array just contains a number of elements. There's no concept of an array being "empty" just because each element happens to contain the default value (0, null, or whatever).

If you want a dynamically sized collection, you should use something like List<T> instead of an array.

If you want to detect whether any element of a collection (whether that's a list, an array or anything else) is a non-default value, you have to do that via looping. (You don't have to loop in your source code, but there'll be looping involved somewhere...)

Upvotes: 5

Related Questions