Skip to content

C# Array or List of anonymous type

25 October 2012

Recently I was ask to create a list of nested anonymous type using C#.
First I’ve dug Google for a while to see what solutions exist there in the net. I was surprised that I failed to find any suitable and simple one. So here is my attempt.

I’ve sat down and dug the anonymous types. Fortunately the solution turned to be simple enough.

The required object had to be an object with some properties and an array of object which structure would be decided on run time. At the end the result object had to be serialized at the end.

Because the structure of these objects is vague the first shot was Anonymous type.

Unfortunately Microsoft documentations statesAnonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

In short anonymous type is immutable – cannot use something like:

var anon = new []{}; // error - can not add properties any more

Though an array of anonymous types can be created as

var anonArray = new[] { new { name = "apple", diam = 4 }, 
                        new { name = "grape", diam = 1 }};

it is created during initialization and cannot be used in a loop where one element of the array is created on each iteration.

So, because Array class implements the System.Collections.Generic.IList, the first natural decision is to use a List of dynamic object and to add anonymous type on each iteration.

So the steps are

res.obj = new List<dynamic>();  // list of anonymous oubject that will be created in a loop
for(int i=0; i<3; i++) // the loop itself
{    // during each iteration a new anonymous object is created
   res.obj.Add( new {iterator=i, 
                     state=String.Format("state of {0}", i.ToString()), 
                     res=true} );
}

The final object has some properties and an array with the previous generated list. It can be passed as a parameter to Json.NET serialization function.

 Console.WriteLine(JsonConvert.SerializeObject(new { rowid= 1, obj= o.ToArray()}));

Following is the CommandLine project including all source rows:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Dynamic;
namespace CmdText
{
   internal class Program
   {
     private static void Main(string[] args)
     {
       dynamic o = new List<dynamic>();
       for (int i = 0; i < 3; i++)
       {
         o.Add( new {iterator=i, state=String.Format("state of {0}", i.ToString()), res=true} );
       }
       Console.WriteLine(JsonConvert.SerializeObject(new { rowid= 1, obj= o.ToArray()}));     }
   }
}

Hoping this might be useful to others I will appreciate your comments.
Advertisements

From → ASP.NET, C#

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: