【问题标题】:Iterate over list of lists by the X coordinate?通过 X 坐标迭代列表列表?
【发布时间】:2019-04-21 13:02:34
【问题描述】:

如果我有这样的列表:

private List<List<int>> tileLayer = new List<List<int>>(50);

我想检查“列”中的所有元素是否都等于-1。 (我知道列只是二维数组的东西,但我不知道如何更好地描述它,或者它是否可能)

如果是,请删除此列及其后面的所有内容。

LINQ 与否,没关系,我不知道该怎么做。

我已经像这样实现了“行”​​的删除:

if (tileLayer[i].All(x => x == -1)) {
    int rowsToDelete = tileLayer.Count - i;
    tileLayer.RemoveRange(i, rowsToDelete);
}

但正如我所说,我不确定如何处理列。也不能使用二维数组,我需要它是动态的。

【问题讨论】:

  • 提供一个示例数组以及所需的 o/p 是什么?

标签: c# arrays linq


【解决方案1】:

这应该可行。将 columnIndex 设置为要检查的列。如果该列中的所有值都是 -1,我们将从您的所有行列表中删除该列。

    int columnIndex = 5; // Set to whatever column you want to check
    var shouldRemove = true;

    // Loop through the columns and check if they equal -1
    foreach (List<int> t in tileLayer)
    {
        if (t[columnIndex] != -1)
        {
            shouldRemove = false;
            break;
        }
    }

    // If all the columns were -1, remove that column
    if (shouldRemove)
    {
        foreach (List<int> t in tileLayer)
        {
            // Remove this column from the List<int>
            t.RemoveRange(columnIndex, t.Count - columnIndex);
        }
    }

【讨论】:

  • 这行得通,但我还需要删除columnIndex 之后的所有列,所以我将其修改为使用RemoveRange 并且它有效!
  • 好的我更新了我的答案以删除索引后的所有列。是的,您可以编写一个包含所有代码的通用函数 CheckAndRemoveColumn(List tileRow, int columnIndex),然后为 4 个列表中的每一个调用该函数 4 次。
【解决方案2】:
  1. 声明一个变量bool delete = false
  2. 使用 for 循环或 foreach 循环遍历外部列表

在循环中:

  1. 检查你想要的列位置的item是否不为null且等于-1
  2. 当它是:设置delete = true并跳出循环

循环之后:

  1. 检查是否delete == true
  2. 如果是:再次使用 for 循环或 foreach 循环遍历外部列表,并删除列位置/后面的元素

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-27
    • 2013-10-29
    • 2020-07-22
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多