找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 3094|回复: 10

[分享] AutoCAD & Dynamic LINQ

[复制链接]

已领礼包: 859个

财富等级: 财运亨通

发表于 2014-6-11 23:03:50 | 显示全部楼层 |阅读模式

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

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

×

  1. /// Excerpts from AcDbLinq.cs  Copyright (c)  2008-2013 Tony Tanzillo



  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using Autodesk.AutoCAD.Runtime;
  7. using Autodesk.AutoCAD.Internal;
  8. using System.Collections;


  9. namespace Autodesk.AutoCAD.DatabaseServices
  10. {
  11.    public static class AcDbLinqExtensions
  12.    {

  13.       /// <summary>
  14.       ///
  15.       /// Returns an object that enumerates all references
  16.       /// to all blocks whose names match the given wildcard
  17.       /// pattern, open for read.
  18.       ///
  19.       /// Requires an active transaction (NOT an OpenCloseTransaction)
  20.       ///
  21.       /// </summary>
  22.       ///  

  23.       public static IEnumerable<BlockReference> GetBlockReferences(
  24.          this Database database,
  25.          string pattern )
  26.       {
  27.          if( string.IsNullOrWhiteSpace( pattern ) )
  28.             throw new ArgumentException( "Requires a wildcard pattern" );
  29.          if( database == null )
  30.             throw new ArgumentNullException( "database" );
  31.          Transaction tr = database.TransactionManager.TopTransaction;
  32.          if( tr == null )
  33.             throw new Autodesk.AutoCAD.Runtime.Exception(
  34.                ErrorStatus.NoActiveTransactions );
  35.          BlockTable blockTable = (BlockTable)
  36.             tr.GetObject( database.BlockTableId, OpenMode.ForRead );
  37.          return blockTable.Cast<ObjectId>()
  38.             .GetObjects<BlockTableRecord>()
  39.             .Where( btr => Utils.WcMatchEx( btr.Name, pattern, true ) )
  40.             .SelectMany( btr => btr.GetBlockReferences() );
  41.       }

  42.          /// <summary>
  43.          /// Gets an object that enumerates all references to the given
  44.          /// BlockTableRecord, including references to anonymous dynamic
  45.          /// BlockTableRecords, open for read.
  46.          /// </summary>

  47.       public static IEnumerable<BlockReference> GetBlockReferences(
  48.          this BlockTableRecord btr,
  49.          OpenMode mode = OpenMode.ForRead,
  50.          bool directOnly = true )
  51.       {
  52.          if( btr == null )
  53.             throw new ArgumentNullException( "btr" );
  54.          var tr = btr.Database.TransactionManager.TopTransaction;

  55.          if( tr == null )
  56.             throw new InvalidOperationException( "No transaction" );
  57.          var ids = btr.GetBlockReferenceIds( directOnly, true );

  58.          int cnt = ids.Count;
  59.          for( int i = 0; i < cnt; i++ )
  60.          {
  61.             yield return (BlockReference)
  62.                tr.GetObject( ids[i], mode, false, false );
  63.          }

  64.          if( btr.IsDynamicBlock )
  65.          {
  66.             BlockTableRecord btr2 = null;
  67.             var blockIds = btr.GetAnonymousBlockIds();
  68.             cnt = blockIds.Count;
  69.             for( int i = 0; i < cnt; i++ )
  70.             {
  71.                btr2 = (BlockTableRecord) tr.GetObject( blockIds[i],
  72.                   OpenMode.ForRead, false, false );
  73.                ids = btr2.GetBlockReferenceIds( directOnly, true );
  74.                int cnt2 = ids.Count;
  75.                for( int j = 0; j < cnt2; j++ )
  76.                {
  77.                   yield return (BlockReference)
  78.                      tr.GetObject( ids[j], mode, false, false );
  79.                }
  80.             }
  81.          }
  82.       }

  83.        /// <summary>
  84.       /// The one, but not only GetObjects<T> (abridged), with due credits
  85.       /// to Jeff H, kaefer, Gile, et. al.
  86.       ///
  87.       /// Returns an object that enumerates all instances of the
  88.       /// given generic argument type, opened accoring to the given
  89.       /// parameters.
  90.       /// </summary>

  91.       public static IEnumerable<T> GetObjects<T>(
  92.           this IEnumerable<ObjectId> ids,
  93.           OpenMode mode = OpenMode.ForRead,
  94.           bool openErased = false,
  95.           bool forceOpenOnLockedLayers = false ) where T : DBObject
  96.       {

  97.          if( ids.Any() )
  98.          {
  99.             TransactionManager tm = ids.First().Database.TransactionManager;

  100.             RXClass rxclass = RXClass.GetClass( typeof( T ) );
  101.             if( typeof( T ) == typeof( DBObject ) )
  102.             {
  103.                foreach( ObjectId id in ids )
  104.                {
  105.                   yield return (T) tm.GetObject( id, mode, openErased,
  106.                      forceOpenOnLockedLayers );
  107.                }
  108.             }

  109.             else if( rxclass.GetHasChildren() )
  110.             {
  111.                foreach( ObjectId id in ids )
  112.                {
  113.                   if( id.ObjectClass.IsDerivedFrom( rxclass ) )
  114.                      yield return (T) tm.GetObject( id, mode, openErased,
  115.                         forceOpenOnLockedLayers );
  116.                }
  117.             }
  118.             else
  119.             {
  120.                foreach( ObjectId id in ids )
  121.                {
  122.                   if( id.ObjectClass == rxclass )
  123.                      yield return (T) tm.GetObject( id, mode, openErased,
  124.                         forceOpenOnLockedLayers );
  125.                }
  126.             }
  127.          }
  128.       }

  129.       // Returns true if at least one RXClass is derived from
  130.       // the given RXClass:

  131.       public static bool GetHasChildren( this RXClass rxclass )
  132.       {
  133.          foreach( DictionaryEntry e in SystemObjects.ClassDictionary )
  134.          {
  135.             if( rxclass == ( (RXClass) e.Value ).MyParent )
  136.                return true;
  137.          }
  138.          return false;
  139.       }
  140.    }

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

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 2014-6-11 23:13:50 | 显示全部楼层

  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.Runtime;

  4. namespace DynamicExpression.Example
  5. {

  6.     public static class DynamicExpressionTest
  7.     {


  8.         /// <summary>
  9.         /// This example requires the DynamicExpression API referenced at:
  10.         /// http://weblogs.asp.net/scottgu/archive/dynamic-linq-part- -using-the-linq-dynamic-query-library.aspx
  11.         ///
  12.         /// The DXTEST command excercises rudimentary use of DynamicExpression to
  13.         /// generate a query expression from a string. In this example, the string
  14.         /// is hard-coded, but might just as easily be derived from user input, etc.,
  15.         /// at runtime in real world use. In essence, DynamicExpression implements
  16.         /// a very basic, rudimentary query language that has a syntax designed to
  17.         /// be familiar to C#, VB and SQL users.
  18.         ///
  19.         /// It should be noted however, that direct use of user-supplied query
  20.         /// strings can be dangerous, without extensive error checking.
  21.         ///
  22.         /// This example will obtain all insertions of the block named 'DOOR'
  23.         /// that are inserted on the layer named 'LEVEL ', and change their
  24.         /// color to red. Note that the dynamic expression is not used to
  25.         /// filter entities by type, as this is done using ObjectIds rather
  26.         /// than opened DBObjects. Hence, the input sequence contains only
  27.         /// BlockReference objects and is the type which the query operates
  28.         /// on and whose properties are used in the query string.
  29.         ///
  30.         /// The example code also requires the AutoCAD Linq Extension Library
  31.         /// which is included (AcDbLinq.cs).
  32.         ///
  33.         /// </summary>

  34.         [CommandMethod("DXTEST")]
  35.         public static void Method()
  36.        {
  37.           Document doc = Application.DocumentManager.MdiActiveDocument;
  38.           using( Transaction tr = doc.TransactionManager.StartTransaction() )
  39.           {
  40.               /// This returns an object that iterates over all BlockRefence
  41.              /// objects in model space:

  42.              var blockrefs = doc.Database.GetModelSpace<BlockReference>().AsQueryable();

  43.              /// There are three basic ways to compose a query string, and which is
  44.              ///  best depends on where the parameters are coming from, and where the
  45.              /// query string itself comes from. For example, only the parameters
  46.              /// may be supplied by the user, or the entire query string may be
  47.              /// supplied by the user.
  48.              ///
  49.                          /// The first way is simply to express it as a literal string, using
  50.              /// escaped double-quotes to surround string constants, thusly:
  51.              /// var query = blockrefs.Where( "Name == "DOOR" && Layer = "LEVEL "" );
  52.              ///
  53.                          /// Another way of doing it is by constructing the entire
  54.                          /// query string using String.Format():
  55.                          ///
  56.                          /// string queryString = string.Format(
  57.                          ///      "Name == "{ }" AND Layer == "{ }"", "DOOR", "LEVEL " );
  58.                          /// var query = blockrefs.Where( queryString );
  59.                          ///
  60.                          /// And lastly, and the one we actually use here, is by using replacements,
  61.                          /// which has the advantage of not requiring string parameters to be
  62.                          /// surrounded by double quotes, presumably because the type of a parameter
  63.                          /// can be inferred by the type of the expression on the left side of the
  64.                          /// relational operator:
  65.                          ///
  66.              var query = blockrefs.Where( "Name == @  && Layer == @ ", "DOOR", "LEVEL " );

  67.              /// The above 'query' var is an IQueryable<BlockReference>, which implicitly
  68.              /// is an IEnumerable<BlockReference> that we can walk using foreach():

  69.              foreach( BlockReference door in query.UpgradeOpen() )
  70.              {
  71.                 door.ColorIndex = 1;
  72.              }
  73.              tr.Commit();
  74.           }
  75.        }

  76.         /// <summary>
  77.         ///
  78.         /// A variation on the above that uses pattern matching for the
  79.         /// layer name, and selects all insertions of 'DOOR' from model
  80.         ///  space, that reside on any layer whose name starts with "LEVEL".
  81.         /// Matching is achieved using the string.StartsWith() method
  82.         /// within the query expression.
  83.         ///
  84.         /// </summary>

  85.         [CommandMethod("DXTEST ")]
  86.         public static void Method()
  87.         {
  88.            Document doc = Application.DocumentManager.MdiActiveDocument;
  89.            using( Transaction tr = doc.TransactionManager.StartTransaction() )
  90.            {
  91.               var blockrefs = doc.Database.GetModelSpace<BlockReference>().AsQueryable();
  92.               var query = blockrefs.Where( "Name == @  && Layer.StartsWith(@ )", "DOOR", "LEVEL" );
  93.               foreach( BlockReference door in query.UpgradeOpen() )
  94.               {
  95.                  door.ColorIndex =  1;
  96.               }
  97.               tr.Commit();
  98.            }
  99.         }
  100.                
  101.         /// <summary>
  102.         /// This is a variation of the above example that uses DynamicExpression
  103.         /// to filter the initial set of ObjectIds and the opened BlockReferences.
  104.         /// </summary>
  105.                
  106.         [CommandMethod("DXTEST ")]
  107.         public static void Method()
  108.         {
  109.            Document doc = Application.DocumentManager.MdiActiveDocument;
  110.            using( Transaction tr = doc.TransactionManager.StartTransaction() )
  111.            {
  112.               var ids = doc.Database.GetModelSpaceIds().AsQueryable();
  113.               var blockrefIds = ids.Where( "ObjectClass.DxfName == @ ", "INSERT" );
  114.               var query = blockrefIds.GetObjects<BlockReference>().AsQueryable()
  115.                  .Where( "Name == @  && Layer.StartsWith(@ )", "DOOR", "LEVEL" );
  116.               foreach( BlockReference door in query.UpgradeOpen() )
  117.               {
  118.                  door.ColorIndex =  1;
  119.               }
  120.                tr.Commit();
  121.            }
  122.         }
  123.     }
  124. }


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

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 859个

财富等级: 财运亨通

 楼主| 发表于 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, 2024-5-22 10:26 , Processed in 0.399504 second(s), 51 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

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