Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to an anonymous list

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.

like image 429
Lali Avatar asked May 14 '14 10:05

Lali


People also ask

How to Add anonymous list c#?

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.

What is an anonymous type in c#?

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.

What is an anonymous object?

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.


1 Answers

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.

like image 145
Sergey Berezovskiy Avatar answered Oct 19 '22 19:10

Sergey Berezovskiy