I\'ve noticed that the new ExpandoObject
implements IDictionary
which has the requisite IEnumerable
I've had the need for a simple ExpandoObject initializer several times before and typically use the following two extension methods to accomplish something like initializer syntax:
public static KeyValuePair WithValue(this string key, object value)
{
return new KeyValuePair(key, value);
}
public static ExpandoObject Init(
this ExpandoObject expando, params KeyValuePair[] values)
{
foreach(KeyValuePair kvp in values)
{
((IDictionary)expando)[kvp.Key] = kvp.Value;
}
return expando;
}
Then you can write the following:
dynamic foo = new ExpandoObject().Init(
"A".WithValue(true),
"B".WithValue("Bar"));
In general I've found that having an extension method to build KeyValuePair
instances from a string key comes in handy. You can obviously change the name to something like Is
so that you can write "Key".Is("Value")
if you need the syntax to be even more terse.