Add item to an anonymous list

anonymous-types, c#

Solution

You should specify property names of anonymous object you create:

myList.Insert(0, new { ProductName = "--All--", ProductId = 0, Priority = 0});

Keep in mind - you should list all properties of anonymous type (names should be same), they should be used in same order, and they should have exactly same types. Otherwise object of different anonymous type will be created.

Problem

I have a list of anonymous type ``` var myList = db.Products.Select(a => new {a.ProductName, a.ProductId, a.Priority}).ToList(); ``` And I want to add an other item to this list like ``` myList.Insert(0, new { "--All--", 0, 0}); //Error: Has some invalid arguments ``` I also tried ``` myList.Add(new { "--All--", 0, 0}); //Error: Has some invalid arguments ``` How can I do that? Edit: I did this after first answer ``` var packageList = db.Products.Select(a => new { a.ProductName, a.ProductId, a.Priority }).ToList(); packageList.Insert(0, new { ProductName = "All", ProductId = 0, Priority = 0 }); ``` but same error again.

Original source