In C#, how do I remove a property from an ExpandoObject?
Asked Answered
T

4

34

Say I have this object:

dynamic foo = new ExpandoObject();
foo.bar = "fizz";
foo.bang = "buzz";

How would I remove foo.bang for example?

I don't want to simply set the property's value to null--for my purposes I need to remove it altogether. Also, I realize that I could create a whole new ExpandoObject by drawing kv pairs from the first, but that would be pretty inefficient.

Trubow answered 23/1, 2013 at 23:52 Comment(0)
G
61

Cast the expando to IDictionary<string, object> and call Remove:

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");
Gualtiero answered 23/1, 2013 at 23:55 Comment(2)
i know this was quite a while ago, but found this today and it helped me get out of an issue where i had to remove all the properties from an dynamic/ExpandoObject contained in a list. it was a literally a one liner (to match the OP, using bang!!): bangItems.All(x => ((IDictionary<string, object>) x).Remove("bang"));Plankton
The code in the answer bangItems.All(x => ((IDictionary<string, object>) x).Remove("bang")); ain't working right? Heads-up that someone might get confused.Beguile
V
35

You can treat the ExpandoObject as an IDictionary<string, object> instead, and then remove it that way:

IDictionary<string, object> map = foo;
map.Remove("Jar");
Veterinary answered 26/11, 2012 at 15:15 Comment(2)
need to remove the member 'Jar' form Foo.. not Foo it self..,Ignescent
@Dhana: So change Foo to Jar :) I've updated the example, but if you understand the way the answer is meant to work, it shouldn't be hard to fix it up yourself...Veterinary
H
17

MSDN Example:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
Horotelic answered 23/1, 2013 at 23:55 Comment(0)
I
8

You can cast it as an IDictionary<string,object>, and then use the explicit Remove method.

IDictionary<string,object> temp = foo;
temp.Remove("bang");
Illiberal answered 23/1, 2013 at 23:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.