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.
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.
Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.
An anonymous object is basically a value that has been created but has no name. Since they have no name, there's no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With