How can I use collection initializer syntax with ExpandoObject?

后端 未结 6 986
温柔的废话
温柔的废话 2021-02-07 08:24

I\'ve noticed that the new ExpandoObject implements IDictionary which has the requisite IEnumerable

6条回答
  •  生来不讨喜
    2021-02-07 09:02

    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.

提交回复
热议问题