Why is IEnumerable losing updated data?

The problem is that IEnumerable is not repeatable. You are performing the projection (community => new ListItem) every time it is enumerated - hence it is a new ListItem each time. Select is a non-buffered deferred projection.

You can fix everything here with the simple addition of a .ToList() to force the data into a single list;

var items = communities.Select(
    community => new ListItem(community.Name, community.Id.ToString())
).ToList();

Now that the data is in the list, you can loop over the list any number of times - it'll always be the same items, and changes will be retained.


It happens, because you use Select:

IEnumerable<ListItem> items = communities
   .Select(community => new ListItem(community.Name, community.Id.ToString()));

which creates new objects every time you iterate through items.


Your problem is that

IEnumerable<ListItem> items = communities
    .Select(community => new ListItem(community.Name, community.Id.ToString()));

creates an IEnumerable that's lazily evaluated -- that is, every time it is enumerated, the original communities sequence is re-enumerated and your Select projection is re-executed per item in that sequence.

If you stick a .ToList() at the end, changing the line to:

IEnumerable<ListItem> items = communities
    .Select(community => new ListItem(community.Name, community.Id.ToString()))
    .ToList();

you will observe a different result. While it is still an IEnumerable, it will no longer be a lazily evaluated one, and the changes you make in it will be observable in later iterations over the same IEnumerable.

Tags:

C#

Linq