Purge/Delete unused layers RhinoCommon c#

Hi
I am trying to write a C# plugin that performs some operations on geometry and I assign layers to the objects. But, I can also see some unused layers which do not contain any geometry object. I want to delete/purge them using my code. These layers could also include active layer if it is unused at the end of all operations.
Questions:

  1. What is a good way to avoid any issues with deleting the active layer? Should I make the last layer that I assign an object through my code the active layer?
  2. How do I code the delete/purge layer method. I think it should have a loop that first checks each layer and the objects assigned to it and deletes the layer until the while loop condition is true.

I am very new to this. Any leads will be appreciated. Thanks

According to the documentation it probably makes sense to check if a layer is active or has a selection before deleting it.

LayerTable.Delete Method (Layer, Boolean) (rhino3d.com) or
LayerTable.Purge Method (Guid, Boolean) (rhino3d.com)

                foreach (var layer in RhinoDoc.ActiveDoc.Layers)
                {
                    RhinoDoc.ActiveDoc.Layers.Delete(layer);
                    layersDeleted++;
                }

if you want to be lazy - you can use a scripted version of rhinos _purge command.
don’t forget the scriptRunner Attribute !!!

if you want to code from scratch - @thomas.k already gave you the entry-point.
you may also want to check if there are obejcts on the layer via
ObjectTable.FindByFilter Method

Make sure to test invisible block-definition objects.