C# 如何验证锯齿状数组中的位置是否为空?

C# How to verify if the position is empty in a jagged array?

所以,我需要制作这个结构

职位:

0 - {2, 5, 7, 8}

1 - {9, 10, 12}

2 - {3, 4}

3 -

我正在尝试使用锯齿状数组来做到这一点(我不知道我是否有更好的方法来做到这一点,也许使用 ArrayList 或 Hashset 但我不确定)。

因此,要将数字插入锯齿状数组,我将接收用户输入(2 个数字)。如果用户键入 1 和 2,我需要将两者都插入到锯齿状数组中。

但为此,我需要检查位置 0 是否为空,如果为空,我需要将用户输入放入锯齿状数组中。如果它不为空,那么它会检查输入是否存在于锯齿状数组中。

所以,我遇到的问题是检查锯齿状数组是否为空。

我试过这个:

static void Main(string[] args)
    {
        Console.WriteLine("Digite a lista de numeros com um espaço de diferença entre cada numero");
        string[] ar_temp = Console.ReadLine().Split(' ');
        int[] ar = Array.ConvertAll(ar_temp, Int32.Parse);
        int tam = ar.Length;
        char fim = 's';


        int[][] jaggedarray = new int[tam / 2][];


        for (int x = 0; x < tam / 2; x++)
        {
            jaggedarray[x] = new int[tam];
        }

        if (jaggedarray[0] is null)
        {
            Console.WriteLine("is null");
        }
        else
        {
            Console.WriteLine("isn't null");
        }
    }

但我得到了错误的输出(它不识别位置为空,即使那里有一个空数组...)

如何检查锯齿状数组的位置是否为空?

空数组不为空。您必须检查数组长度:

if (jaggedarray[0] == null || jaggedarray[0].Length == 0)
{
    Console.WriteLine("é nulo");
}
else
{
    Console.WriteLine("Não é nulo");
}

此外,您可以简化代码:

Console.WriteLine(jaggedarray[0] == null || jaggedarray[0].Length == 0 ? "é nulo" : "Não é nulo");

只需将 is null 替换为 == null,如下所示:

int[][] jaggedarray = new int[tam / 2][];

for(int x = 0; x < tam/2; x++)
{
    jaggedarray[x] = new int[tam];
}

if (jaggedarray[0] == null)
{
    Console.WriteLine("é nulo");
}
else
{
    Console.WriteLine("Não é nulo");
}