简体   繁体   English

如何在 IEnumerable 中添加项目?

[英]How to add Items in IEnumerable?

I have this code and I would like to add Item in the list and I am doing like this.我有这个代码,我想在列表中添加项目,我正在这样做。

IEnumerable<SelectListItem> note = new List<SelectListItem>();
var selectList = new SelectListItem
      {
          Text = Convert.ToString(amount.Key), 
          Value Convert.ToString(amount.Value)  
      };
note.ToList().Add(selectList);

I am unable to Add item.我无法添加项目。

The ToList() call creates a brand new list, which is not connected to the original list. ToList()调用创建一个全新的列表,该列表未连接到原始列表。 No changes you make to the new list will be propagated back to the original.您对新列表所做的任何更改都不会传播回原始列表。

As for adding, you cannot add items to the IEnumerable<T> .至于添加,您不能向IEnumerable<T>添加项目。 It all depends on that you're trying to do with your code, but why do you use IEnumerable<SelectListItem> instead of IList<SelectListItem> , which has an Add() operation.这完全取决于您尝试使用代码进行操作,但是为什么要使用IEnumerable<SelectListItem>而不是IList<SelectListItem> ,后者具有Add()操作。 Since IList<T> is-a IEnumerable<T> , you will be able to pass the note to any method that expects an IEnumerable<T> .由于IList<T>IEnumerable<T> ,您将能够将note传递给任何需要IEnumerable<T>

When you say ToList() it's not casting it, it's creating a whole new list and that's what you're adding to.当您说 ToList() 时,它不是在投射它,而是在创建一个全新的列表,这就是您要添加的列表。

What you want is to avoid the weird casting you do to start with (make note a List not an IEnumerable) and then add to that directly你想要的是避免你开始时做的奇怪的转换(注意一个列表而不是一个 IEnumerable)然后直接添加到它

List<SelectListItem> note = new List<SelectListItem>()
var selectList = new SelectListItem{Text = Convert.ToString(amount.Key), Value Convert.ToString(amount.Value)                }
note.Add(selectList)

Not that it makes any sense to do that but if you really want to assign your list to an IEnumerable to begin with you can still cast it later when you need the added functionality as follow:并不是说这样做没有任何意义,但是如果您真的想将您的列表分配给一个 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)
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();

The easy way would be to make note a List immediately: 最简单的方法是立即note一个列表:

IEnumerable<SelectListItem> note = new List<SelectListItem>();
...
//note.ToList().Add(selectList)
note.Add(selectList);

but assuming you do need to have an IEnumerable: 但是假设您确实需要一个IEnumerable:

note = note.ToList().Add(selectList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM