简体   繁体   中英

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. 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> . 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. Since IList<T> is-a IEnumerable<T> , you will be able to pass the note to any method that expects an 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.

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

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<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:

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

but assuming you do need to have an IEnumerable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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