简体   繁体   中英

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.

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. 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? 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 :

  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 (var item in jaggedArray.IterateNonNull()) {
    // ...
}

If this is the first you see yield return , read this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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