Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically removing a member from Expando /dynamic object [duplicate]

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.

like image 986
Matt Cashatt Avatar asked Jan 23 '13 23:01

Matt Cashatt


4 Answers

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

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");
like image 127
Jon Avatar answered Oct 24 '22 01:10

Jon


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");
like image 34
Jon Skeet Avatar answered Oct 23 '22 23:10

Jon Skeet


MSDN Example:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
like image 14
Simon Whitehead Avatar answered Oct 23 '22 23:10

Simon Whitehead


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

IDictionary<string,object> temp = foo;
temp.Remove("bang");
like image 8
Reed Copsey Avatar answered Oct 23 '22 23:10

Reed Copsey