Reputation: 543
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.
Upvotes: 1
Views: 18352
Reputation: 11
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();
Upvotes: 0
Reputation: 3603
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)
Upvotes: 0
Reputation: 115731
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>
.
Upvotes: 3