user1 user1 - 1 year ago 101
C# Question

Can I flatten a List<object> to an anonymous object with properties for each item?

I am trying flatten a list of objects into an annonymous objects.

For example lets say i have:

List<Tag> tags = new List<Tag>();
tags.Add(new Tag(id: "Tag1", value:true));
tags.Add(new Tag(id: "Tag2", value:true));
tags.Add(new Tag(id: "Tag3", value:false));

I would then like to flatten this list to an anonymous object like:

tags.Select(x => new
Tag1 = true,
Tag2 = true,
Tag3 = false

is what I am trying to do possible on a bigger / more generic scale?

Answer Source

Yes using an ExpandoObject:

var o = new ExpandoObject() as IDictionary<string,object>;

o.Add("Tag1", true);
o.Add("Tag2", true);
o.Add("Tag3", false);

In this way you are actually adding properties to the ExpandoObject

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download