[Solved] Can’t modify List inside an IEnumerable? [duplicate]


Yes you can’t! The IEnumerable generates new Lists every time it is evaluated; it says so right there in your code:

.Select(x => new List<int>{x});

When you call Dump(), it is evaluated. When you call First(), it’s evaluated again. Then Dump again. All new Lists!

If you evaluate the IEnumerable before putting it in the list variable (e.g. by putting it into an array), it would work:

var list = new int[]{1,2,3}.Select(x => new List<int>{x}).ToArray();
list.Dump();
list.First().Insert(0, 5);
list.Dump();

1

solved Can’t modify List inside an IEnumerable? [duplicate]