找回密码
 立即注册
查看: 4042|回复: 10

[分享] AutoCAD & Dynamic LINQ

[复制链接]
发表于 2014-6-11 23:03:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
/// Excerpts from AcDbLinq.cs Copyright (c) 2008-2013 Tony Tanzillo using System; using System.Collections.Generic; using System.Linq; using System.Text; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.Internal; using System.Collections; namespace Autodesk.AutoCAD.DatabaseServices { public static class AcDbLinqExtensions { /// <summary>
展开
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
 楼主| 发表于 2014-6-11 23:05:27 | 显示全部楼层
           RXClass rxc = RXClass.GetClass(typeof(BlockReference));
            return btr.Cast<ObjectId>()
                .Where(id => id.ObjectClass == rxc)
                .Select(id => (BlockReference)id.GetObject(OpenMode.ForRead))
                .Where(br =>
                    (br.IsDynamicBlock ?
                    ((BlockTableRecord)br.DynamicBlockTableRecord.GetObject(OpenMode.ForRead)).Name :
                    br.Name) == pattern);;   
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-11 23:13:50 | 显示全部楼层
using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Runtime; namespace DynamicExpression.Example { public static class DynamicExpressionTest { /// <summary> /// This example requires the DynamicExpression API referenced at: /// http://weblogs.asp.net/scottgu/archive/dynamic-linq-part- -using-the-linq-dynamic-query-library.aspx /// /// The DXTEST command excercises rudimentary use of DynamicExpression to /// generate a query expression from a string. In this example, the string /// is hard-coded, but might just as easily be derived from user input, etc., /// at runtime in real world use. In essence, DynamicExpression implements
展开
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-11 23:15:00 | 显示全部楼层
    static class Extensions
    {
        public static T GetObject<T>(this ObjectId id) where T : DBObject
        {
            return (T)id.GetObject(OpenMode.ForRead);
        }

        public static IEnumerable<T> GetObjects<T>(this SymbolTable source) where T : SymbolTableRecord
        {
            foreach (ObjectId id in source)
                yield return (T)id.GetObject(OpenMode.ForRead);
        }

        public static IEnumerable<BlockReference> GetBlockReferences(this BlockTableRecord btr, ObjectId ownerId)
        {
            return btr.GetStaticReferences(ownerId)
                .Concat(btr.GetAnonymousBlockIds()
                    .Cast<ObjectId>()
                    .SelectMany(id => id.GetObject<BlockTableRecord>().GetStaticReferences(ownerId)));
        }

        public static IEnumerable<BlockReference> GetBlockReferences(this Database db, string pattern, ObjectId ownerId)
        {
            return db.BlockTableId
                .GetObject<BlockTable>()
                .GetObjects<BlockTableRecord>()
                .Where(btr => Autodesk.AutoCAD.Internal.Utils.WcMatch(btr.Name, pattern))
                .SelectMany(btr => btr.GetBlockReferences(ownerId));
        }

        static IEnumerable<BlockReference> GetStaticReferences(this BlockTableRecord btr, ObjectId ownerId)
        {
            return btr.GetBlockReferenceIds(true, false)
                .Cast<ObjectId>()
                .Select(id => id.GetObject<BlockReference>())
                .Where(br => br.OwnerId == ownerId);
        }
    }
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 00:37:38 | 显示全部楼层
var currentDocument = Application.DocumentManager.MdiActiveDocument;
var editor = currentDocument.Editor;
var database = editor.Document.Database;

var result = editor.SelectAll();

using (var transaction = database.TransactionManager.StartTransaction())
{
    foreach (var id in result.Value.GetObjectIds())
    {

        var obj = transaction.GetObject(id, OpenMode.ForRead);

        var properties = TypeDescriptor.GetProperties(obj.AcadObject).Cast<PropertyDescriptor>().OrderBy(prop => prop.Name);


        writer.WriteLine("{0} ID:{1}", obj.GetType().Name, obj.Id);
        writer.WriteLine("\r\n\r\n");

        foreach (var property in properties)
        {
            var propertyObject = property.GetValue(obj.AcadObject);
            writer.WriteLine("  {0} = {1}", property.Name, propertyObject);
        }

        writer.Write("\r\n\r\n\r\n");
    }
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 00:39:31 | 显示全部楼层
// Get all items from drawing Database. All ObjectIds will grouped by types;
Database db = Application.DocumentManager.MdiActiveDocument.Database;           
Dictionary<string, List<ObjectId>> dict = new Dictionary<string, List<ObjectId>>();
using (Transaction t = db.TransactionManager.StartTransaction()) {
    for (long i = db.BlockTableId.Handle.Value; i < db.Handseed.Value; i++) {
        ObjectId id = ObjectId.Null;
        Handle h = new Handle(i);
        if (db.TryGetObjectId(h, out id)) {
            string type = id.ObjectClass.Name;
            if (!dict.Keys.Contains(type))
                dict.Add(type, new List<ObjectId>());
            dict[type].Add(id);
        }
    }
    t.Commit();
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 01:18:37 | 显示全部楼层
[CommandMethod("GetAllRectangles")]
public static void GetCircles()
{
    Document document = Application.DocumentManager.MdiActiveDocument;
    Database database = document.Database;
    Editor editor = document.Editor;
    RXClass rxClassPoly = RXClass.GetClass(typeof (Polyline));
    var count = 0;
       
    using (Transaction transaction = document.TransactionManager.StartOpenCloseTransaction())
    {
        var blockTable = transaction.GetObject(database.BlockTableId, OpenMode.ForWrite, false) as BlockTable;
        var blocktableRecord = transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForRead, false) as BlockTableRecord;
        foreach (ObjectId objectId in blocktableRecord)
        {
            if (objectId.ObjectClass == rxClassPoly)
            {
                var poly = transaction.GetObject(objectId, OpenMode.ForRead) as Polyline;
                if (poly.Layer == "0" && poly != null)
                {
                    if (poly.NumberOfVertices == 4)
                    {
                        var line0 = poly.GetLineSegmentAt(0);
                        var line1 = poly.GetLineSegmentAt(1);
                        var line2 = poly.GetLineSegmentAt(2);
                        var line3 = poly.GetLineSegmentAt(3);

                        if (line0.IsPerpendicularTo(line1) && line1.IsPerpendicularTo(line2) &&
                            line2.IsPerpendicularTo(line3) && line3.IsPerpendicularTo(line0))
                        {
                            count = count + 1;

                            // Put all your rectangle processing code here.

                        }
                     }
                }
            }
        }
        transaction.Commit();
    }
    editor.WriteMessage(string.Format("\r\nFound {0} rectangles!", count));
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 22:06:55 | 显示全部楼层
private static List<BlockReference> GetBlockRefs(string blkName, Document dwg)
{
    List<BlockReference> blks = null;

    Database db = dwg.Database;
    using (Transaction tran = db.TransactionManager.StartTransaction())
    {
        BlockTable tbl =
            (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead);

        //Get modelspace BloclTableRecord
        BlockTableRecord br =
            (BlockTableRecord)tran.GetObject(tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead);

        //Cast the BlockTableRecord into IEnumeralbe<T> collection
        IEnumerable<ObjectId> b = br.Cast<ObjectId>();

        //Use lambda extension method
        blks = b.Where(id => id.ObjectClass.DxfName.ToUpper() == "INSERT")
               .Select(id => GetBlockRef(id, tran)).ToList<BlockReference>();

        //Use LINQ statement. This is more readable
        blks = (from id in b
                where id.ObjectClass.DxfName.ToUpper() == "INSERT"
                select GetBlockRef(id, tran)).ToList<BlockReference>();

        tran.Commit();
    }

    //return only blockreferences with name starting with blkName with lambda extension method
    return blks.Where(b => b.Name.ToUpper() == blkName.ToUpper()).ToList();

    //Or return with LINQ statement
    return (from b in blks where b.Name.ToUpper() == blkName.ToUpper() select b).ToList();
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 22:09:25 | 显示全部楼层
private static string[] GetBlockNameList(Document dwg)
{
    string[] names = null;

    Database db = dwg.Database;
    using (Transaction tran = db.TransactionManager.StartTransaction())
    {
        BlockTable tbl =
            (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead);

        //Get modelspace BloclTableRecord
        BlockTableRecord br =
            (BlockTableRecord)tran.GetObject(tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead);

        //Cast the BlockTableRecord into IEnumeralbe<T> collection
        IEnumerable<ObjectId> b = br.Cast<ObjectId>();

        //Use lambda extension method
        names = b.Where(id => id.ObjectClass.DxfName.ToUpper() == "INSERT")
                .Select(id => GetBlockRef(id, tran).Name).Distinct().ToArray();

        //Use LINQ statement. This is more readable
        names = (from id in b
                 where id.ObjectClass.DxfName.ToUpper().Contains("INSERT")
                 select GetBlockRef(id, tran).Name).Distinct().ToArray();

        tran.Commit();
    }

    return names;
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 22:11:41 | 显示全部楼层
本帖最后由 csharp 于 2014-6-23 22:12 编辑

private List<ObjectId> GetCertainEntityIDs(Database db)
{
    List<ObjectId> ids = null;
    using (Transaction tran = db.TransactionManager.StartTransaction())
    {
        BlockTable tbl =
            (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead);
        //Get modelspace BloclTableRecord
        BlockTableRecord br =
            (BlockTableRecord)tran.GetObject(tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead);
        //Cast the BlockTableRecord into IEnumeralbe<T> collection
        IEnumerable<ObjectId> b = br.Cast<ObjectId>();
        //==============search certain entity========================//
        //"LINE" for line
        //"LWPOLYLINE" for polyline
        //"CIRCLE" for circle
        //"INSERT" for block reference
        //...
        //We can use "||" (or) to search for more then one entity types
        //============================================================//
        //Use lambda extension method
        ids = b.Where(id => id.ObjectClass.DxfName.ToUpper() == "LINE" ||
                      id.ObjectClass.DxfName.ToUpper() == "LWPOLYLINE").ToList<ObjectId>();
        //Use LINQ statement. This is more readable
        ids = (from id in b
               where id.ObjectClass.DxfName.ToUpper() == "LINE" ||
               id.ObjectClass.DxfName.ToUpper() == "LWPOLYLINE"
               select id).ToList<ObjectId>();
        tran.Commit();
    }
    return ids;
}

论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-6-23 22:13:46 | 显示全部楼层
private static string[] GetEntityType(Document dwg)
{
    string[] types = null;

    Database db = dwg.Database;
    using (Transaction tran = db.TransactionManager.StartTransaction())
    {
        BlockTable tbl =
            (BlockTable)tran.GetObject(db.BlockTableId, OpenMode.ForRead);

        //Get modelspace BloclTableRecord
        BlockTableRecord br =
            (BlockTableRecord)tran.GetObject(tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead);

        //Cast the BlockTableRecord into IEnumeralbe<T> collection
        IEnumerable<ObjectId> b = br.Cast<ObjectId>();

        //Use lambda extension method
        types = b.Select(id => id.ObjectClass.DxfName).Distinct().ToArray();

        //Use LINQ statement. This is more readable
        types = (from id in b select id.ObjectClass.DxfName).Distinct().ToArray();

        tran.Commit();
    }

    return types;
}
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|申请友链|Archiver|手机版|小黑屋|辽公网安备|晓东CAD家园 ( 辽ICP备15016793号 )

GMT+8, 2026-12-1 21:33 , Processed in 0.221083 second(s), 48 queries , Gzip On.

Powered by Discuz! X5.0

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表