将项目添加到匿名列表 [英] Add item to an anonymous list

查看:65
本文介绍了将项目添加到匿名列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个匿名类型列表

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

我也尝试过

myList.Add(new { "--All--", 0, 0}); //Error: Has some invalid arguments

我该怎么办?

我在第一次回答后就做了

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. Otherwise object of different anonymous type will be created.

这篇关于将项目添加到匿名列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆