Many times you need to create a temporary list of anonymous type objects. For small tasks, like binding a list to a DropDownList control. At that moment you don't want to define a separate class just to keep two properties (i.e. Id & Name)
and bind it to the DropDownList's DataSource.
There could be numerous ways to define list of anonymous types and all of these need to infer type from somewhere. I will write some of them here which you can use to create generic list.
-
First create the object(s) of anonymous type and then pass it to an array and call
ToList()method.var o1 = new { Id = 1, Name = "Foo" }; var o2 = new { Id = 2, Name = "Bar" }; var list = new[] { o1, o2 }.ToList(); -
Define a list of
dynamicand then populate with anonymous objects.List<dynamic> list = new List<dynamic>(); var o1 = new { Id = 1, Name = "Foo" }; var o2 = new { Id = 2, Name = "Bar" }; list.Add(01); list.Add(02); -
Define a generic method accepting
params T[], and returnnew List<T>. Pass objects of anonymous type to this method and it will create the List<T>.//Define method public static List<T> CreateList<T>(params T[] items) { return new List<T>(items); } //create anonymous objects and call above method var o1 = new { Id = 1, Name = "Foo" }; var o2 = new { Id = 2, Name = "Bar" }; var list = CreateList(o1, o2); -
You can use
Select()method onEnumerable.Range()to project anonymous objects and then callToList()method. Once empty list is created, then start adding objects.var list = Enumerable.Range(0, 0).Select(e => new { Id = 0, Name = ""}).ToList(); list.Add(new { Id = 1, Name = "Foo" } ); list.Add(new { Id = 2, Name = "Bar" } ); -
Enumerable.Repeat()method can also do the trick.var list = Enumerable.Repeat(new { Id = 0, Name = "" }, 0).ToList(); list.Add(new { Id = 1, Name = "Foo" } ); list.Add(new { Id = 2, Name = "Bar" } ); -
Select()projection method can also use on simple string.var list = "".Select( t => new {Id = 0, Name = ""} ).ToList(); list.Add(new { Id = 1, Name = "Foo" } ); list.Add(new { Id = 2, Name = "Bar" } );