tags:

views:

225

answers:

2
+2  Q: 

C# collection

int[] mylist = { 2, 4, 5 };
IEnumerable<int> list1 = mylist;
list1.ToList().Add(1);
// why 1 does not get addedto list1??
+18  A: 

Why would it? ToList() generates a new List and the value '1' gets added to it. Since you don't store the return, the new list then gets tossed when it's out of scope.

ToList() doesn't change the original IEnumerable object list1 or give a new representation (it would be called AsList() if it did).

ctacke
IEnumerable<int> newList = list1.ToList().Add(1); // The code you want
jrcs3
This is like the commonly made first timer mistake with String.Replace().
Kev
Not quite the same mistake as String.Replace(). The string class is immutable and the List is not. So while .Replace() is creating a new string .Add() is actually adding to a List object. But it's the List created from ToList() and not the original array.
Joseph Daigle
+1  A: 

You need to :

int[] mylist = { 2, 4, 5 };
IEnumerable<int> list1 = mylist;
List<int> lst = list1.ToList();
lst.Add(1);
mylist = lst.ToArray();
Andrei Rinea
Or just "List<int> lst = myList.ToList();". The IEnumerable variable is not needed.
Hosam Aly
That's right Hosam, I just appended to his code to make it simpler.
Andrei Rinea