1

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.

H H
  • 263,252
  • 30
  • 330
  • 514
user3661407
  • 525
  • 3
  • 9
  • 18

3 Answers3

3

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

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • Thank you Anton. I did it as you mentioned and It is working. The reason behind doing with IEnumerable I was jus thinking out of the box – user3661407 Jun 08 '14 at 13:49
0

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)
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • I would like to make IEnumerable note = new List() and then want to add item. Do you have any idea – user3661407 Jun 08 '14 at 13:40
  • Why do you want that? this go against what you said you want to do, an IEnumerable is just that, something you can enumerate, you can NOT add to an IEnumerable, IEnumerable simply doesn't expose this functionality – Ronan Thibaudau Jun 08 '14 at 13:40
0
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();
Siyaz
  • 11