Question

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

Solution

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

OTHER TIPS

You need to :

int[] mylist = { 2, 4, 5 };
IEnumerable<int> list1 = mylist;
List<int> lst = list1.ToList();
lst.Add(1);
mylist = lst.ToArray();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top