How can I convert an ExpandoObject to Dictionary in C#?
Asked Answered
M

2

10

I'm using Jint to execute JavaScript in a Xamarin app. Jint is converting an associative array into an ExpandoObject. How do I use this object? Ideally, I'd like to get a dictionary of the data out of it.

JavaScript returns:

return {blah:abc, bleh:xyz};

Debugger of Object that Jint returns looks like:

enter image description here

Mathian answered 16/9, 2015 at 20:50 Comment(2)
@bzlm: Not a dupe. This is specific how-to question about creating a dictionary from ExpandoObject.Conlee
The only way to do it I've found is: ((IDictionary<string, object>)result).ToDictionary(nvp => nvp.Key, nvp => nvp.Value)Intercalation
R
35

It already IS a dictionary. Just implicitly cast it:

IDictionary<string, object> dictionary_object = expando_object;

And then use it like one. BTW: this is also the reason why recursive's solution works.

Roodepoortmaraisburg answered 16/9, 2015 at 21:29 Comment(1)
This doesn't change the json behavior. It still serializes as [{"Key":"Property1Name", "Value":"Property1Value"}, {"Key":"Property2Name", "Value":"Property2Value"}]Intercalation
C
18

Just pass it to the constructor.

var dictionary = new Dictionary<string, object>(result);
Conlee answered 16/9, 2015 at 20:53 Comment(4)
If result is object, which on expando I believe it is, then this won't compile. It will find the constructor that takes an int instead.Intercalation
Everything is an object. But result is dynamically typed and the concrete type implements IDictionary. Try it and you'll see.Conlee
I did. It won't compile like that. I have a list of expando objects and Json(results.Data.Select(o => new Dictionary<string, object>(o)) won't compile. I get error: "CS1503 Argument 1: cannot convert from 'object' to 'int'". Hovering over o tells me that parameter o is object. So, results.Data.Select(o => ((IDictionary<string, object>)o).ToDictionary(nvp => nvp.Key, nvp => nvp.Value)) is the only way I could get it to work.Intercalation
The dictionary constructor takes an IDictionary, which ExpandoObject is. However if the static declaration of your variable is object, the compiler can't verify it. ExpandoObject instances are usually declared dynamic. That would work. In your example, you cast o to (IDictionary<string, object>).Conlee

© 2022 - 2024 — McMap. All rights reserved.