cool breeze
cool breeze

Reputation: 4811

Creating an anonymous object, how to use a loop to add items

I'm currently creating a anonymous object like this, it works fine so far.

var users = new
{
   action = "users",
   newbies = new[]
   {
      new
      {
         email = "abc",
         username = "def",
         location = "ghi"
      }
   }
}

Now I need to modify this, by adding more properties to the inner object.
I have a List that has users in it, which represents the users friends.

List<User> friends = ...

So the inner object should look something like:

new

{
  email = "abc",
  username = "def",
  location = "ghi",
  friend1email = "[email protected]",
  friend2username = "f1",
  friend2email = "[email protected]",
  friend2username = "f2",
}

except I would need to get this using the LIst, so looping like:

foreach(var user in friends)
{

}

How can I generate this type of a anonymous object when I need to loop?

Note: I can't change the format here, I know it is silly but that is how it is.

Update

How can I do this using the ExpandoObject?

Upvotes: 1

Views: 1560

Answers (2)

Sam Axe
Sam Axe

Reputation: 33738

You could build up your object structure in JSON ( building a string is easy ), and then use a JSON deserializer (install NewtonSoft.JSON via NuGet) to convert it to an object.

Upvotes: 3

Pol
Pol

Reputation: 5134

You can't do it with anonymous object but you can do it with dynamic object if you treat it as a dictionary.

Upvotes: 2

Related Questions