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.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111

4 Answers4

60

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

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 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) x).Remove("bang")); – jim tollan May 12 '21 at 11:49
  • 1
    The code in the answer ```bangItems.All(x => ((IDictionary) x).Remove("bang"));``` ain't working right? Heads-up that someone might get confused. – Saiyaff Farouk Aug 04 '21 at 20:44
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");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • need to remove the member 'Jar' form Foo.. not Foo it self.., – Dhanapal Nov 26 '12 at 15:16
  • 1
    @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... – Jon Skeet Nov 26 '12 at 15:16
15

MSDN Example:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
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");
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373