int[] mylist = { 2, 4, 5 };
IEnumerable<int> list1 = mylist;
list1.ToList().Add(1);
// why 1 does not get addedto list1??
views:
225answers:
2
+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
2009-01-05 03:01:33
IEnumerable<int> newList = list1.ToList().Add(1); // The code you want
jrcs3
2009-01-05 03:05:51
This is like the commonly made first timer mistake with String.Replace().
Kev
2009-01-05 04:08:11
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
2009-01-05 06:21:09
+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
2009-01-05 14:34:23
Or just "List<int> lst = myList.ToList();". The IEnumerable variable is not needed.
Hosam Aly
2009-01-05 14:59:12
That's right Hosam, I just appended to his code to make it simpler.
Andrei Rinea
2009-01-05 23:31:23