2

I need to create an object that has properties that are named dynamically like:

<users>
  <user1name>john</user1name>
  <user2name>max</user2name>
  <user3name>asdf</user3name>
</users>

Is this possible?

cool breeze
  • 4,461
  • 5
  • 38
  • 67

1 Answers1

11

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;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Great, as an addition, how can I create a list of these? So in your example, I would want to add expando to a list of expando's. I'm getting an error saying I can't add a IDictionary to a expandoobject. – cool breeze Jul 22 '15 at 15:30
  • 2
    @cool: So cast back to ExpandoObject. If that doesn't work, ask a new question with details. – Jon Skeet Jul 22 '15 at 15:32
  • @Jon Skeet: In the above response, if there exists elements with the same name and value, ExpandoObject return an error : Same Name Value already exists in Objects... What could be the solution for allowing repeat name/ value in expando Objects... refer question Link – Mufaddal Dec 06 '18 at 10:50
  • @Jon Skeet : Above Question Link : https://stackoverflow.com/questions/53649959/allow-same-name-value-for-dynamic-json-creation-using-expandoobject-and-idiction – Mufaddal Dec 06 '18 at 11:05