C# 如何在IEnumerable中添加项?
我有这个代码,我想在列表中添加项目,我这样做C# 如何在IEnumerable中添加项?,c#,C#,我有这个代码,我想在列表中添加项目,我这样做 IEnumerable<SelectListItem> note = new List<SelectListItem>(); var selectList = new SelectListItem { Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value) }; no
IEnumerable<SelectListItem> note = new List<SelectListItem>();
var selectList = new SelectListItem
{
Text = Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
note.ToList().Add(selectList);
IEnumerable note=new List();
var selectList=新建SelectListItem
{
Text=Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
note.ToList().Add(选择列表);
我无法添加项。当您说ToList()时,它不是在强制转换它,而是在创建一个全新的列表,这就是您要添加的内容
你想要的是避免你一开始就做的奇怪的角色转换(注意列表而不是IEnumerable),然后直接添加到列表中
List<SelectListItem> note = new List<SelectListItem>()
var selectList = new SelectListItem{Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value) }
note.Add(selectList)
列表注释=新列表()
var selectList=new SelectListItem{Text=Convert.ToString(amount.Key),Value Convert.ToString(amount.Value)}
备注:添加(选择列表)
这并不是说这样做有任何意义,但如果您真的想首先将列表分配给IEnumerable,您仍然可以在以后需要添加以下功能时强制转换它:
IEnumerable<SelectListItem> note = new List<SelectListItem>()
var selectList = new SelectListItem{Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value) }
((List<SelectListItem>)note).Add(selectList)
IEnumerable note=新列表()
var selectList=new SelectListItem{Text=Convert.ToString(amount.Key),Value Convert.ToString(amount.Value)}
((列表)注释)。添加(选择列表)
调用ToList()
将创建一个全新的列表,该列表未连接到原始列表。对新列表所做的任何更改都不会传播回原始列表
至于添加,您不能将项目添加到IEnumerable
。这完全取决于您试图对代码执行的操作,但为什么要使用IEnumerable
而不是具有Add()
操作的IList
。由于IList
是一个IEnumerable
,因此您可以将注释
传递给任何需要IEnumerable
的方法;
var selectList=新建SelectListItem
{
Text=Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
注:添加(选择列表);
var notes=note.AsNumerable();
我们更喜欢正确的编译代码(包括
;
),我想让IEnumerable note=new List()然后添加项。你有什么想法吗?你为什么要那样?这与你说的相反,IEnumerable只是,你可以列举的东西,你不能添加到IEnumerable,IEnumerable只是没有公开这个功能谢谢Anton。我按照你说的那样做了,而且很有效。使用IEnumerable的原因我只是想跳出框框然后你可以使用notes如果你想使用你的收藏。我相信你的意思是note.AsEnumerable()
。否则它不会编译。
List<SelectListItem> note = new List<SelectListItem>();
var selectList = new SelectListItem
{
Text = Convert.ToString(amount.Key),
Value Convert.ToString(amount.Value)
};
note.Add(selectList);
var notes = note.AsNumerable();