Skip to content

Cookbook : Iteration

myd7349 edited this page Jun 16, 2021 · 2 revisions

Iterating over all objects in the file

The anonymous function passed to visit allows us to save information back into dynamic List<T>. Without this we would have to pin an array that is preallocated.

      List<string> datasetNames = new List<string>();
      List<string> groupNames = new List<string>();
      var rootId = H5G.open(fileId, "/");

      H5O.visit(fileId, H5.index_t.NAME, H5.iter_order_t.INC, new H5O.iterate_t(
        delegate(hid_t objectId, IntPtr namePtr, ref H5O.info_t info, IntPtr op_data)
        {
          string objectName = Marshal.PtrToStringAnsi(namePtr);
          H5O.info_t gInfo = new H5O.info_t();
          H5O.get_info_by_name(objectId, objectName, ref gInfo);

          if (gInfo.type == H5O.type_t.DATASET)
          {
            datasetNames.Add(objectName);
          }
          else if (gInfo.type == H5O.type_t.GROUP)
          {
            groupNames.Add(objectName);
          }
          return 0;
        }), new IntPtr());
      
      H5G.close(rootId);

      // Print out the information that we found
      foreach (var line in datasetNames)
      {
        Debug.WriteLine(line);
      }