Thursday 26 May 2011

Creating a generic list of an anonymous type ?!?

Yesterday I was wondering how to create a generic list of an anonymous type, something like this:
var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = new List();
At the beginning I though this was impossible, but the resolution is closer than it appears:

var employee = new { FirstName = "Jan", LastName = "Kowalski" };
var employeeList = (new[] {employee}).ToList();
employeeList.Clear();

We can extend it to create factory creating those lists:
public static List<T> CreateList<T>(T itemOftype)
{
   List<T> newList = new List<T>();
   return newList;
}

No comments:

Post a Comment