Thursday, March 29, 2012

Linq and Civil 3D 2013

With Civil 3D 2013 also comes changes to the API. AutoCAD and Civil 3D are now being built with .NET Framework 4.0. One of the benefits of this change is the ability to use Linq to query information. Linq is short for Language Integrated Query and is created by Microsoft. With the .NET programming the API is getting away from storing information where it is easily accessed, but is located by getting ObjectIds and then having you get the objects from those ObjectIds. One example of this is the GetAlignmentIds() method of the CivilDocument.

Linq provides a fairly compact way to get the information out of those ObjectIds. If I was to try to try to see if an alignment name already exists I’d have to do a for each loop which takes quite a bit of code to perform. With Linq I can take that same process and turn it into a compact query.

bool nameExists = (from objId in civDoc.GetAlignmentIds().Cast<ObjectId>()
                               select (objId.GetObject(OpenMode.ForRead) as Alignment).Name).Contains(proposedAlignmentName);

I’ve gone from at least 5 lines of code down to two (if the code fit on this web page).

The Linq query is taking the ObjectIds from the list, converting the ObjectId to get the alignment, and then seeing if the name I’m trying to use exists. If it does then I get a true, if not I get a false value. Another benefit is that the query isn’t always run when it is hit in the code. In most cases it waits until the information is needed. This may provide performance improvements when running your code and an error happens before you need the information.

1 comment:

Logan Belten said...

With .net framework, Linq is easily usable, both these together is going to provide a good help to AutoCAD and Civil 3D. LINQ query is now a first class terminology build, just like classes, events, methods and so on.


Blog Widget by LinkWithin