如何从锯齿状数组中以更简单的方式返回数据?

时间:2018-03-22 06:27:53

标签: c#

我创建了一个工厂类,允许用户调用方法Generate,并通过一些我不希望用户处理的逻辑填充锯齿状数组。

由于工厂生成的网格布局类型,很多索引都为空。

但我不希望用户必须迭代两个数组索引并检查null。无论如何都要简化这个以便用户迭代这个数组,而不必担心它。

例如,要迭代他们当前必须执行的数据:

for (int i = Map.MapData.Length - 1; i >= 0; --i)
{
    for (int j = Map.MapData[i].Length - 1; j >= 0; --j)
    {
         // would rather they didn't have to check for null
         if (Map.MapData[i][j] == null) continue;

         // do stuff with data
    }
}

这不是所有用户友好的。有没有办法让数据对用户更加线性,比如在数据上使用a?为了达到这个目的,我并不完全确定我在寻找什么,希望有人能指出我正确的方向。

由于

2 个答案:

答案 0 :(得分:2)

查询集合时(在您的情况下,您希望所有不是null个项目)尝试使用 Linq

  var NotNullItems = Map
    .SelectMany(line => line      // From each line
       .Where(x => x != null));   // Filter out all null items

  foreach (var item in NotNullItems) {
    // do stuff with data
  }

答案 1 :(得分:1)

如果你只想循环遍历数组的元素并丢弃索引,你可以做一个扩展方法:

public static class JaggedArrayExtensions {
    public static IEnumerable<T> IterateNonNull<T>(this T[][] array) where T : class {
        for (int i = array.Length - 1; i >= 0; --i)
        {
            for (int j = array[i].Length - 1; j >= 0; --j)
            {
                // would rather they didn't have to check for null
                if (array[i][j] == null) continue;

                yield return array[i][j];
            }
        }
    }
}

现在,您可以使用foreach循环遍历您的锯齿状数组:

foreach (var item in jaggedArray.IterateNonNull()) {
    // ...
}

如果这是您第一次看到yield return,请阅读this

相关问题