StackOverflowVeryHelpful StackOverflowVeryHelpful - 2 months ago 35
C# Question

Dynamic object in c# where the key has a $ sign

How to create a dynamic object of the below representation in c#. Guid is passed in as a parameter

{$addToSet : {childFolders: "Guid"}}

I tried this :

dynamic expando = new ExpandoObject();
expando.$addSet = new ExpandoObject() as dynamic; // This line gives me error on visual studio . Unexpected character '$'

Jim Jim

With ExpandoObject Class

dynamic expando = new ExpandoObject();

((IDictionary<string, object>)expando).Add("$addSet", new ExpandoObject());

var addSet = ((IDictionary<string, object>)expando)["$addSet"] as dynamic;

addSet.childFolders = "Guid";

With Json.Net

dynamic obj = new JObject();
obj["$addSet"] = new JObject();
var addSet = obj["$addSet"];
addSet.cildFolders = "Guid";