user1 user1 - 1 month ago 4x
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?


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