简体   繁体   English

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

[英]How to return data in a more simplified manner from a jagged array?

I've created a factory class which allows the user to call a method Generate and it populates a jagged array via some logic that generally I don't want the user to deal with. 我创建了一个工厂类,该类允许用户调用Generate方法,并且它通过一些我通常不希望用户处理的逻辑来填充锯齿状数组。

A lot of index's are null because of the type of grid layout that the factory generates. 由于工厂生成的网格布局的类型,很多索引为空。

But I don't want the user to have to iterate both array indexes and check for null. 但是我不希望用户必须迭代两个数组索引并检查是否为null。 Is there anyway to simplify this for a user to iterate this array without them needing to worry about it. 无论如何,有没有要简化此操作的方法,以便用户可以迭代该数组而无需担心。

For example, to iterate the data they currently have to do: 例如,要迭代他们当前必须执行的数据:

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

This isn't all that user friendly. 这不是所有的用户友好。 Is there a way I can make the data be more linear to the user, like using a for each on the data? 有没有一种方法可以使数据对用户更线性,就像对数据中的每个使用a一样? I'm not entirely sure what I am looking for in order to achieve this, hope some one can point me in the right direction. 我不能完全确定要实现此目标需要什么,希望有人可以指出正确的方向。

Thanks 谢谢

When querying collections (in your case you want all not null items) try using Linq : 查询集合时(在您的情况下,您希望所有都不为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
  }

If you just want to loop through the elements of the array and discard the indices, you can do an extension method: 如果只想遍历数组的元素并放弃索引,则可以执行扩展方法:

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

Now you can loop through your jagged array with a foreach loop: 现在,您可以使用foreach循环foreach锯齿状数组:

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

If this is the first you see yield return , read this . 如果这是您第一次看到yield return ,请阅读此内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM