Identifying the type of an object (AutoCAD .net API)

Let’s say you have an array of ObjectIDs. And you want to filter out and keep all the lines. How would you do that?

If you said you’d create a transaction, open the object, etc then please listen up and save yourself some grief. Did you know that the ObjectId class as a property which tells you what type of Object it represents without the need for you to actually open the object in a transaction? Sounds pretty cool right?

  ObjectId id = GetID(); // the ID is got
  id.ObjectClass;      // now we can access the type which the ID holds.

Here’s a little static method I copied from Keane which does the job:

  private static ObjectId[] OnlyOfClass(ObjectId[] ids, RXClass c)
  {
    return ids.Where(id => { return id.ObjectClass == c; }).ToArray();
  }

And how would you call it?

  var Outputids = OnlyOfClass( inputObjectIds, RXClass.GetClass(typeof(Line));  

Or if you wanted something a la LINQ:

private List<ObjectId> GetDimensions(Database db)
        {
            List<ObjectId> dimensionIds = new List<ObjectId>();

            using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;

                dimensionIds =  ms.Cast<ObjectId>()
                                .Where( id => id.ObjectClass == RXClass.GetClass(typeof(AlignedDimension)))
                                .ToList() ;
                tr.Commit();
            }

            return dimensionIds;
        }

Gotta keep on learning and getting better and better!

Written on March 1, 2017