从字符串[,]中删除空值

Joh*_*don 4 c# arrays string multidimensional-array

我有一个在c#中定义的字符串数组

string[,] options = new string[100,3];
Run Code Online (Sandbox Code Playgroud)

在整个代码中,它会填充数据,但并不总是填充.

因此,如果我有80个部分填充它,20个部分没有填充.20个部分中包含空值或最后有60个空值.是否有一种简单的方法来调整数组的大小,以便在填充数组后,数组与之相同

String[,] options = new string[80,3];
Run Code Online (Sandbox Code Playgroud)

它必须根据它找到的第一组3个零点的位置来调整大小.

如果这是一个锯齿状的阵列,我会做的

options = options.Where(x => x != null).ToArray();
Run Code Online (Sandbox Code Playgroud)

xan*_*tos 7

方法很长,因为它必须检查每一行两次...

public static string[,] RemoveEmptyRows(string[,] strs)
{
    int length1 = strs.GetLength(0);
    int length2 = strs.GetLength(1);

    // First we count the non-emtpy rows
    int nonEmpty = 0;

    for (int i = 0; i < length1; i++)
    {
        for (int j = 0; j < length2; j++)
        {
            if (strs[i, j] != null)
            {
                nonEmpty++;
                break;
            }
        }
    }

    // Then we create an array of the right size
    string[,] strs2 = new string[nonEmpty, length2];

    for (int i1 = 0, i2 = 0; i2 < nonEmpty; i1++)
    {
        for (int j = 0; j < length2; j++)
        {
            if (strs[i1, j] != null)
            {
                // If the i1 row is not empty, we copy it
                for (int k = 0; k < length2; k++)
                {
                    strs2[i2, k] = strs[i1, k];
                }

                i2++;
                break;
            }
        }
    }

    return strs2;
}
Run Code Online (Sandbox Code Playgroud)

使用它像:

string[,] options = new string[100, 3];
options[1, 0] = "Foo";
options[3, 1] = "Bar";
options[90, 2] = "fiz";
options = RemoveEmptyRows(options);
Run Code Online (Sandbox Code Playgroud)

正如阿列克谢所建议的,还有另一种方法:

public static string[,] RemoveEmptyRows2(string[,] strs)
{
    int length1 = strs.GetLength(0);
    int length2 = strs.GetLength(1);

    // First we put somewhere a list of the indexes of the non-emtpy rows
    var nonEmpty = new List<int>();

    for (int i = 0; i < length1; i++)
    {
        for (int j = 0; j < length2; j++)
        {
            if (strs[i, j] != null)
            {
                nonEmpty.Add(i);
                break;
            }
        }
    }

    // Then we create an array of the right size
    string[,] strs2 = new string[nonEmpty.Count, length2];

    // And we copy the rows from strs to strs2, using the nonEmpty
    // list of indexes
    for (int i1 = 0; i1 < nonEmpty.Count; i1++)
    {
        int i2 = nonEmpty[i1];

        for (int j = 0; j < length2; j++)
        {
            strs2[i1, j] = strs[i2, j];
        }
    }

    return strs2;
}
Run Code Online (Sandbox Code Playgroud)

在权衡记忆与时间的关系中,选择时间.它可能更快,因为它不必检查每一行两次,但它使用更多的内存,因为它在某处放置了非空索引的列表.