Hi,
I had to build a similar class, here's the way I did it (I only add an Indexor and a Constructor from ObjectId I didn't needed when I wrote this).
I needed a class implementing IEqualityComparer too, so that the Linq GroupBy() extension method can be used with a 'BlockAttribute' collection.
public class BlockAttribute
{
private string _name;
private Dictionary<string, string> _atts;
public string Name
{
get { return _name; }
}
public Dictionary<string, string> Attributes
{
get { return _atts; }
}
public string this[string key]
{
get { return _atts[key.ToUpper()]; }
}
public BlockAttribute(BlockReference br)
{
SetProperties(br);
}
public BlockAttribute(ObjectId id)
{
Document doc = AcAp.DocumentManager.MdiActiveDocument;
using (Transaction tr = doc.TransactionManager.StartTransaction())
{
SetProperties(tr.GetObject(id, OpenMode.ForRead) as BlockReference);
}
}
new public string ToString()
{
if (_atts != null && _atts.Count > 0)
return string.Format("{0}: {1}",
_name,
_atts.Select(a => string.Format("{0}={1}", a.Key, a.Value))
.Aggregate((a, b) => string.Format("{0}; {1}", a, b)));
return _name;
}
private void SetProperties(BlockReference br)
{
if (br == null) return;
_name = br.IsDynamicBlock ?
((BlockTableRecord)br.DynamicBlockTableRecord.GetObject(OpenMode.ForRead)).Name :
br.Name;
_atts = new Dictionary<string, string>();
foreach (ObjectId id in br.AttributeCollection)
{
AttributeReference att = (AttributeReference)id.GetObject(OpenMode.ForRead);
_atts.Add(att.Tag.ToUpper(), att.TextString);
}
}
}
public class BlockAttributeEqualityComparer : IEqualityComparer<BlockAttribute>
{
public bool Equals(BlockAttribute x, BlockAttribute y)
{
if (!x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase)) return false;
foreach (KeyValuePair<string, string> att in x.Attributes)
{
if (!y.Attributes.ContainsKey(att.Key)) return false;
if (!y.Attributes[att.Key].Equals(att.Value)) return false;
}
return true;
}
public int GetHashCode(BlockAttribute obj)
{
return base.GetHashCode();
}
}