wrschneider
wrschneider

Reputation: 18770

Index into arbitrary nested Dictionary/List structure in C#

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.

Upvotes: 0

Views: 326

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

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.

Upvotes: 1

Related Questions