Один из подходов, который мне помог, - это метод расширения ToExpando()
, разработанный Яном Цуй ( source ):
public static class DictionaryExtensionMethods
{
/// <summary>
/// Extension method that turns a dictionary of string and object to an ExpandoObject
/// </summary>
public static ExpandoObject ToExpando(this IDictionary<string, object> dictionary)
{
var expando = new ExpandoObject();
var expandoDic = (IDictionary<string, object>) expando;
// go through the items in the dictionary and copy over the key value pairs)
foreach (var kvp in dictionary)
{
// if the value can also be turned into an ExpandoObject, then do it!
if (kvp.Value is IDictionary<string, object>)
{
var expandoValue = ((IDictionary<string, object>) kvp.Value).ToExpando();
expandoDic.Add(kvp.Key, expandoValue);
}
else if (kvp.Value is ICollection)
{
// iterate through the collection and convert any strin-object dictionaries
// along the way into expando objects
var itemList = new List<object>();
foreach (var item in (ICollection) kvp.Value)
{
if (item is IDictionary<string, object>)
{
var expandoItem = ((IDictionary<string, object>) item).ToExpando();
itemList.Add(expandoItem);
}
else
{
itemList.Add(item);
}
}
expandoDic.Add(kvp.Key, itemList);
}
else
{
expandoDic.Add(kvp);
}
}
return expando;
}
}
Пример использования:
public const string XEntry = "ifXEntry";
public static readonly dynamic XEntryItems = new Dictionary<string, object>
{
{ "Name", XEntry + ".1" },
{ "InMulticastPkts", XEntry + ".2" },
{ "InBroadcastPkts", XEntry + ".3" },
{ "OutMulticastPkts", XEntry + ".4" },
{ "OutBroadcastPkts", XEntry + ".5" },
{ "HCInOctets", XEntry + ".6" },
{ "HCInUcastPkts", XEntry + ".7" },
{ "HCInMulticastPkts", XEntry + ".8" },
{ "HCInBroadcastPkts", XEntry + ".9" },
{ "HCOutOctets", XEntry + ".10" },
{ "HCOutUcastPkts", XEntry + ".11" },
{ "HCOutMulticastPkts", XEntry + ".12" },
{ "HCOutBroadcastPkts", XEntry + ".13" },
{ "LinkUpDownTrapEnable", XEntry + ".14" },
{ "HighSpeed", XEntry + ".15" },
{ "PromiscuousMode", XEntry + ".16" },
{ "ConnectorPresent", XEntry + ".17" },
{ "Alias", XEntry + ".18" },
{ "CounterDiscontinuityTime", XEntry + ".19" },
}.ToExpando();
Затем можно использовать такие свойства, как XEntryItems.Name
.
PS: Пожалуйста, проголосуйте здесь за поддержку инициализаторов объектов в ExpandoObjects.