-1

This is my c# code to identify the block containing attribute in autocad. In my dwg file there is repeated no.of attribute i want to display each selected attribute only once and avoid duplicate values.

[CommandMethod("NLTAG")]
public void ListAttributes()
{
    Document acDoc = Application.DocumentManager.MdiActiveDocument;
    Editor ed=Application.DocumentManager.MdiActiveDocument.Editor;
    Database db = HostApplicationServices.WorkingDatabase;
    Transaction tr = db.TransactionManager.StartTransaction();

    try
    {
        TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.Start, "INSERT") };
        SelectionFilter filter = new SelectionFilter(filList);
        // Do nothing if selection is unsuccessful
        if (res.Status != PromptStatus.OK)
            return;

        SelectionSet selSet = res.Value;
        ObjectId[] idArray = selSet.GetObjectIds();

        foreach (ObjectId blkId in idArray)
        {
            BlockReference blkRef = (BlockReference)tr.GetObject(blkId, OpenMode.ForRead);
            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
            ////ed.WriteMessage(
            ////  "\nBlock: " + btr.Name
            ////);
            btr.Dispose();

            AttributeCollection attCol = blkRef.AttributeCollection;
            AttributeCollection parts = blkRef.AttributeCollection;
            foreach (ObjectId attId in attCol)
            {
                AttributeReference attRef(AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);
                string str = ("\n " + attRef.TextString);//here i get duplicate value
                ed.WriteMessage(str);
            }
        }
        tr.Commit();
    }
    catch (Autodesk.AutoCAD.Runtime.Exception ex)
    {
        ed.WriteMessage(("Exception: " + ex.Message));
    }
    finally
    {
        tr.Dispose();
    }
}
Ajay
  • 27
  • 8

1 Answers1

0

Are there too many attributes? You could just chuck them in a list and then get the distinct values?

var inMemList = new List<string>();

foreach (ObjectId attId in attCol)
{
    AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);
    inMemList.Add(attRef.TextString);
}


foreach(var text in inMemList.Distinct())
    ed.WriteMessage(string.Format("\n {0}", text));

Of course this has not been optimised but the point is that you will need to "pre-process" the output.

Augusto Goncalves
  • 8,493
  • 2
  • 17
  • 44
Leo
  • 14,625
  • 2
  • 37
  • 55
  • @Ajay hopefully you didn't copy my answer as it was. I edited it...what error are you getting? – Leo Jul 27 '16 at 04:46
  • error at foreach loop aatRef not define can you plz edit my code with your suggestions that will good for me. – Ajay Jul 27 '16 at 04:48
  • @Ajay that's a complete different error...you should open a different question – Leo Jul 27 '16 at 05:20