Tuesday, 13 September 2011

Collections of anonymous types

A friend at work today wondered if we could make a list of anonymously-typed objects. It feels like we should be able to -- judging by LINQ -- but there didn't seem to be a mechanism for doing it direct. However, you can create a seed array and generate a list from that:
using System;
using System.Linq;

namespace ListOfAnonymous
    class Program
        static void Main(string[] args)
            var seedArray = new[] { new { Foo = "dingo", Bar = "bingo" } };
            var theList = seedArray.ToList();
            theList.Add(new { Foo = "ringo", Bar = "zingo" });
            theList.ForEach(x => Console.WriteLine(x.Foo));
Better, you get compile-time checking of the instance you're adding to the new list -- this doesn't work:
            theList.Add(new { Foo = "ringo" });    // fail ....
And using a similar extension method you can create a dictionary, choosing a certain property as the key:
            var theDict = seedArray.ToDictionary(x => x.Foo);
            theDict["ringo"] = new {Foo = "ringo", Bar = "zingo"};
            theDict.Keys.ToList().ForEach(x => Console.WriteLine(theDict[x]));
after doing which you end up with a dictionary mapping your key property to instances of the anonymous type. This is a bit fiddly -- having to specify the keyname twice -- but if you have an anonymous instance already created then you can just use the right key property explicitly.

No comments: