public class MyApp
{
[CommandMethod("ADDXDATA")]
static public void AddXdata()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
try
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
PromptEntityResult ers = ed.GetEntity("Pick entity ");
Entity ent = (Entity)tr.GetObject(ers.ObjectId, OpenMode.ForWrite);
RegAppTable regTable = (RegAppTable)tr.GetObject(db.RegAppTableId, OpenMode.ForRead);
if (!regTable.Has("TESTEAPP"))
{
regTable.UpgradeOpen();
RegAppTableRecord app = new RegAppTableRecord();
app.Name = "TESTEAPP";
regTable.Add(app);
tr.AddNewlyCreatedDBObject(app, true);
}
Dictionary<DxfCode, object> xd = new Dictionary<DxfCode, object>
{
{ DxfCode.ExtendedDataRegAppName, "TESTEAPP" },
{ DxfCode.ExtendedDataInteger16, 1000 }
};
List<TypedValue> tvslist = new List<TypedValue>();
foreach (var key in xd.Keys)
{
tvslist.Append(new TypedValue((int)key, xd[key]));
}
TypedValue[] tvs = tvslist.ToArray();
ResultBuffer rb = new ResultBuffer(tvs);
ent.XData = rb;
tr.Commit();
}
}
catch (Exception ex)
{
Application.ShowAlertDialog(ex.Message);
}
}
}
I'm trying to use a standard C# dictionary as a container for passing AutoCAD API TypedValue for the .Xdata property get. If I just put the TypedValue array directly inside the
new ResultBuffer(new TypedValue(DxfCode.ExtendedDataRegAppName, "TESTEAPP"), new TypedValue(DxfCode.ExtendedDataInteger16, 1000));
it works just fine, whats makes no sense. What am I missing, any thoughts?
I get it! Seems I trying to use the LINQ .Append() on a List, and that's was not working. Use .Add() instead. Now I am studying more about LINQ, because it can be tricky sometimes.
Replaced:
tvslist.Append(new TypedValue((int)key, xd[key]));
With:
tvslist.Add(new TypedValue((int)key, xd[key]));
And worked just fine.
The LINQ Append(element) always returns a new IEnumeable with the element appended on tail. And here, I wanted modify the existent List so the .Add() its the right way. More on the diference about Append() and Add() can be found here: Difference between a List's Add and Append method?