Let us look at a cool AutoCAD .NET coding gadget in this post. It uses the cool modern LINQ technology to filter AutoCAD entities with various criteria, e.g. finding all circles with red color and dashed line type on a specific layer. In the old days without the LINQ technology, this is a not so straightforward and actually an error prone task. We generally had to use many out-of-dated ADS stuffs such as result buffer, DXF codes, selection set, and different sets of relational and logical operators which are not familiar to C# or C++ programmers at all, though they have been wrapped a bit and renamed in the AutoCAD .NET as such, TypedValue, DxfCode, SelectionFilter, etc. With the wonderful LINQ technology handy, we do not have to care about these unfriendly legacy stuffs anymore. We can make the same work done more nicely, naturally and efficiently with less code using the LINQ technology. Here we go.
- private static ObjectId[] FindCircles(short color, string layer, string linetype)
- {
- ObjectId[] ret;
- using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
- {
- BlockTable bt = tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;
- BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
- var v = from ObjectId id in btr
- where OpenObject(tr, id) is Circle &&
- OpenObject(tr, id).ColorIndex == color &&
- OpenObject(tr, id).Layer == layer &&
- OpenObject(tr, id).Linetype == linetype
- select id;
- ret = v.ToArray();
- tr.Commit();
- }
- return ret;
- }
- private static Entity cachedEnt = null;
- private static ObjectId cachedId = ObjectId.Null;
- private static Entity OpenObject(Transaction tr, ObjectId id)
- {
- if (cachedId != id || cachedEnt == null)
- cachedEnt = tr.GetObject(id, OpenMode.ForRead) as Entity;
- return cachedEnt;
- }
- [CommandMethod("TestLinqInAutoCAD")]
- public static void TestLinqInAutoCAD_Method()
- {
- Editor ed = MgdAcApplication.DocumentManager.MdiActiveDocument.Editor;
- try
- {
- ObjectId[] ids = FindCircles(1, "TEST", "DASHED");
- ed.WriteMessage(string.Format("There are {0} circles with red color and dashed line type on the layer 'test'.", ids.Length));
- }
- catch (System.Exception ex)
- {
- ed.WriteMessage(ex.ToString());
- }
- }
- In case there are some circles meeting the filtering criteria in the current drawing, the command may print out something onto the AutoCAD command line window as follows:
- Command: TestLinqInAutoCAD
- There are 76 circles with red color and dashed line type on the layer 'test'.
- Enjoy it! More coding gadgets will be created and demonstrated in the future. Please stay tuned.
- The leading edge AutoCAD .NET Addin Wizard (AcadNetAddinWizard) provides various project wizards, item wizards, coders and widgets to help program AutoCAD .NET addins.
复制代码
|