0

I have a structure that is a Dictionary<string,object>, where the values are either strings, nested Dictionary<string,object> or a Lists of these nested dictionaries. This structure is mostly a temp area to build something that will be converted to JSON.

If I want to make assertions on the contents of that structure, though, I can't easily do something like

foo["bar"][0]["baz"][1][2]["quux"] 

without ridiculous type casting, and because the structure is not perfectly recursive, a solution like this (Recursive generic types) doesn't work.

What is the best option here?

Should I look at dynamic? Should I replace the Dictionary instances with anonymous objects?
Should I looked at ExpandoObject? etc.

Community
  • 1
  • 1
wrschneider
  • 17,913
  • 16
  • 96
  • 176
  • It looks like you don't care about type safety here, so you could definitely use `dynamic`. – MarcinJuraszek Oct 31 '15 at 02:04
  • Yes, `dynamic` is what I want in this case - that should be the accepted answer. The whole point is to effectively let me use duck typing with indexing into dictionaries/lists. Only downside is that you still need casts for LINQ extension methods like `Select` and `Where` to work. – wrschneider Nov 01 '15 at 02:10

1 Answers1

1

Since you are converting it to Json anyway just use Json.NET it lets you do foo["bar"][0]["baz"][1][2]["quux"] out of the box and has other nice features like turning your object in to a properly formatted Json string once you are ready to turn it in to that.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431