Using Linq to Filter Objects in your current space - (AutoCad .net API)
A brilliant example which I basically restructured from some code Gilles provided:
[CommandMethod("Circle")]
public void Circle()
{
// we want all circles larger than 10 which exist in the current space.
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
var CirclesLargerThan10 = btr
.Cast<ObjectId>()
.Select(id => tr.GetObject(id, OpenMode.ForRead) as Circle)
.Where(ent => ent != null)
.Where(circle => circle.Radius > 10);
tr.Commit();
}
}
You can use Linq to filter down objects. It’s certainly much easier to read than 100 nested if statements. Also, something I didn’t know was that the BlockTableRecord class implements IEnumerable. This can come in very handy :)
I hope you learned something, as I did.
It was so good that I had to make a post right away.
Written on December 21, 2016