Sunday, August 07, 2011

How to create list of anonymous types

I was writing a method and I needed to loop through a collection of objects, collecting a couple of fields of those objects based on some business conditions and store them into a temporary data structure. Anonymous type came into my mind right away. But how to store those anonymous types into a list? I googled without giving much thought and guess what – there is indeed a way and i liked it.

var listOfAnonymoustTypes = new[] { new { Id=1, Name="Name" }}.ToList();
That’s it. It is that easy and intuitive. Following contains the detailed discussion on this topic.