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

标签 c# arrays string multidimensional-array

我在 C# 中定义了一个字符串数组

string[,] options = new string[100,3];

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

因此,如果我有 80 个部分已填充,20 个部分未填充。这 20 个部分中有空值或末尾有 60 个空值。有没有一种简单的方法来调整数组的大小,以便在填充后数组与

String[,] options = new string[80,3];

它必须根据它找到的第一组 3 个空值的位置调整大小。

如果这是一个锯齿状的数组我会做

options = options.Where(x => x != null).ToArray();

最佳答案

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

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;
}

像这样使用它:

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

正如 Alexei 所建议的,还有另一种方法:

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;
}

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

关于c# - 从字符串 [,] 中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103831/

相关文章:

c# - 如何将区域性更改为 .Net 中的 DateTimepicker 或日历控件

c# - Asp.net 网页不垂直滚动

具有 "where constraint"定义的 C# 泛型 "any generic type"?

python - 追加列表、数组、矩阵

c# - 获取从 C# 调用的 COM 方法的错误消息

php - mysql 多维数组查询

arrays - 从没有列名的 Postgres 行构建 JSON

java - 关于java文件关闭

c - 附加到字符串作为输入参数

python - 如何删除字符串列表中的特殊字符并将其拆分为单独的元素