c# - 有效跳过二维字符串数组中的空白行

标签 c# linq multidimensional-array

<分区>

考虑像这样的二维数组:

enter image description here

使用以下代码跳过空行:

public static string[,] SkipBlankRows(this string[,] array2D)
{
    var columns = array2D.GetLength(1);
    var rows = array2D.GetLength(0);
    var temp = new List<string[]>();

    for (var r = 0; r < rows; r++)
    {
        var row = new string[columns];
        for (var c = 0; c < columns; c++)
        {
            row[c] = array2D[r, c];
        }
        if (row.All(itm => string.IsNullOrWhiteSpace(itm)))
            continue;
        temp.Add(row);
    }

    string[,] result = new string[temp.Count(), columns];
    rows = temp.Count();

    for (int r = 0; r < rows; r++)
    {
        var row = temp[r];
        for (var c = 0; c < row.Length; c++)
        {
            result[r,c]=row[c];
        }
    }
    return result;
}

用法:

void Main()
{
    var x = new string[,] { { "", "", "" }, { "", "X", "" }, { "X", "X", "X" }, { "", "", "" }, {"X","","X"}, {"X","X","X"}};
    var y = x.SkipBlankRows();
}

结果:

结果应该是 字符串的二维数组,其中不会有空行。

enter image description here

代码对我来说看起来很尴尬,是否可以做得更好,例如涉及linq?

最佳答案

你可以使用 LINQ得到string[,]IEnumerable<IEnumerable<string>>删除空行,然后放入 IEnumerable<IEnumerable<string>>回到string[,] .我不知道有什么办法可以使用 LINQ转换一个IEnumerable<IEnumerable<string>>进入string[,] ,所以我只使用了嵌套 foreach循环。

public static string[,] SkipBlankRows(this string[,] array2D)
{
    int columnCount = array2D.GetLength(1);

    var withoutEmptyLines = array2D
        .Cast<string>()  // Flatten the 2D array to an IEnumerable<string>
        .Select((str, idx) => new { str, idx }) // Select the string with its index
        .GroupBy(obj => obj.idx / columnCount) // Group the items into groups of "columnCount" items
        .Select(grp => grp.Select(obj => obj.str)) // Select the groups into an IEnumerable<IEnumerable<string>>
        .Where(strs => !strs.All(str => string.IsNullOrWhiteSpace(str))); // Filter empty rows;

    // Put the IEnumerable<IEnumerable<string>> into a string[,].
    var result = new string[withoutEmptyLines.Count(), columnCount];
    int rowIdx = 0;
    foreach (var row in withoutEmptyLines)
    {
        int colIdx = 0;
        foreach (var col in row)
        {
            result[rowIdx, colIdx++] = col;
        }
        rowIdx++;
    }

    return result;
}

关于c# - 有效跳过二维字符串数组中的空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60322812/

相关文章:

c# - 编码 C# 类型以调用 C++ IDispatch 接口(interface)导致类型不匹配

c# - 如何在asp.net core中添加多个身份和多个角色

c# - 使用 linq 返回带有 list<object> 成员的对象

asp.net - 设置gridview的页数

php - 多维数组输出php mysql

c++ - 在函数之间的堆上传递数组时导致此运行时错误的原因,c++

c# - IEnumerable<T> 等于 ICollection<T> 类型检查

linq - 使用 Linq 按数组内的数组分组

c# - 对目录中的文件名进行排序,给出错误排序的结果

r - 用m维数组选择N维数组的子集?