Dynamically Adding Properties to an Expandoobject

Dynamically adding properties to an ExpandoObject


dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

Add property to ExpandoObject with the same name as a string

ExpandoObject implements IDictionary<string, object>:

((IDictionary<string, object>)obj)[propName] = propValue

I don't know off the top of my head whether you can use the indexer syntax with a dynamic reference (i.e., without the cast), but you can certainly try it and find out.

How to add properties at runtime dynamically to the object c#?


dynamic expando = new ExpandoObject();

// Add properties dynamically to expando
AddProperty(expando, "Language", "English");

public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
{
// ExpandoObject supports IDictionary so we can extend it like this
var expandoDict = expando as IDictionary<string, object>;
if (expandoDict.ContainsKey(propertyName))
expandoDict[propertyName] = propertyValue;
else
expandoDict.Add(propertyName, propertyValue);
}

Thanks to Jay Hilyard and Stephen Teilhet

source: https://www.oreilly.com/content/building-c-objects-dynamically/

Using ExpandoObject when property names are dynamic, is this possible?

Yes, absolutely. Just use it as an IDictionary<string, object> to populate:

IDictionary<string, object> expando = new ExpandoObject();
expando["foo"] = "bar";

dynamic d = expando;
Console.WriteLine(d.foo); // bar

In your XML case, you'd loop over the elements, e.g.

var doc = XDocument.Load(file);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var element in doc.Root.Elements())
{
expando[element.Name.LocalName] = (string) element;
}

C# - Adding objects dynamically (adding dynamic property names)

Rather than creating an ExpandoObject or some other dynamic type, you could create a List<Dictionary<string, object>> where each Dictionary<string, object> contains the name/value pairs you want to serialize. Then serialize to JSON using Json.NET (or JavaScriptSerializer, though that is less flexible):

        var list = new List<Dictionary<string, object>>();

// Build a dictionary entry using a dictionary initializer: https://msdn.microsoft.com/en-us/library/bb531208.aspx
list.Add(new Dictionary<string, object> { { "ID", 1 }, {"Product", "Pie"}, {"Days", 1}, {"QTY", 65} });

// Build a dictionary entry incrementally
// See https://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx
var dict = new Dictionary<string, object>();
dict["ID"] = 2;
dict["Product"] = "Melons";
dict["Days"] = 5;
dict["QTY"] = 12;
list.Add(dict);

Console.WriteLine(JsonConvert.SerializeObject(list, Formatting.Indented));
Console.WriteLine(new JavaScriptSerializer().Serialize(list));

The first outputs:

[
{
"ID": 1,
"Product": "Pie",
"Days": 1,
"QTY": 65
},
{
"ID": 2,
"Product": "Melons",
"Days": 5,
"QTY": 12
}
]

The second outputs the same without the indentation:

[{"ID":1,"Product":"Pie","Days":1,"QTY":65},{"ID":2,"Product":"Melons","Days":5,"QTY":12}]

Dynamically read properties from c# expando object

You can get the properties by using something like:

public static void CreateWorkbook(List<ExpandoObject> ItemList)
{
foreach(var item in ItemList)
{
IDictionary<string, object> propertyValues = item;

foreach (var property in propertyValues.Keys)
{
Console.WriteLine(String.Format("{0} : {1}", property, propertyValues[property]));
}
}
}

Dynamically adding properties to a dynamic object?


dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1


Related Topics



Leave a reply



Submit