1

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?

5
  • Are you saying you want a dynamic number of friendXemail properties based on how many friends the associated list contains? Commented Jul 21, 2015 at 21:39
  • @DStanley yes that is what I am saying. Commented Jul 21, 2015 at 21:50
  • You should consider using a key value pair container like a Dictionary Commented Jul 21, 2015 at 21:54
  • @DStanley how about if I try the expando object? Commented Jul 21, 2015 at 21:55
  • 1
    It depends on what you want to do with it - ExpandoObject does not have true "properties" - it just relies on dynamic to resolve them at run time. So if you have code that expect properties (like mapping or serialization) it may not work, Commented Jul 21, 2015 at 22:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.