newer 发表于 2021-1-9 22:08:24

Finding out if a layer contains entities



问题:
Is there a quick way to find out if there are entities associated with a layer?

解答:
I have a simple solution for you. We can use the Purge() method of the class Database to check whether the layer is able to be purged or not. If it is, it is not associated with any objects; if not, it is. The Purge() method accepts an ObjectId collection argument. If the layers in the collection are able to be purged, they will remain in the collection; otherwise will be removed from the collection. Therefore, we can check whether the layer id is still in the collection or not to know whether it is able to be purged or not. Here, we can just check whether the count of the collection is zero or not since we can add the layer to the collection.

The following code does so exactly. Please make a layer “1” and draw something on it before testing the command.


public void CheckLayerDependence()
{
Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
try
{
    Database db = HostApplicationServices.WorkingDatabase;

    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
      ObjectId ltId = db.LayerTableId;
      LayerTable lt = (LayerTable)tr.GetObject(ltId, OpenMode.ForRead);
      if ( lt.Has("1") )
      {
      ObjectId ltrId = lt["1"];

      ObjectIdCollection idCol = new ObjectIdCollection();
      idCol.Add(ltrId);
      db.Purge(idCol);

      if (idCol.Count != 0)
      {
          ed.WriteMessage("\nThe layer 1 does not have dependences.");
      }
      else
      {
          ed.WriteMessage("\nThe layer 1 have dependences.");
      }
      }
      else
      {
      ed.WriteMessage("\nThe layer 1 does not exist!");
      }

      tr.Commit();
    }
}
catch (System.Exception ex)
{
    ed.WriteMessage(ex.Message);
}
}


aisong220 发表于 2021-1-11 08:08:53

{:1_10:}{:1_10:}

aisong220 发表于 2021-1-11 08:23:58

{:1_10:}{:1_10:}
页: [1]
查看完整版本: Finding out if a layer contains entities