I’m seeing a strange behavior in my code, here’s an analogous example using apples and persons, but the code is basically the same:
List<Apple> apples = ...
var selectableApples = apples.Select(a => new SelectableApple { SelectedByPerson = null, Apple = a });
foreach (Person person in persons)
{
foreach (var unselectedApple in selectableApples.Where(aa => aa.SelectedByPerson == null))
{
if (/*the person satisfies some conditions*/)
{
// This gets executed like 100 times:
unselectedApple.SelectedByPerson = person;
}
}
}
foreach (var selectedApple in selectableApples.Where(aa => aa.SelectedByPerson != null))
{
Unreachable code - the collection is empty... WTF???
}
The SelectableApple class is just a plain C# class without logic, and public getters and setters for all the properties.
Why does this happen?
Thanks in advance!
The
selectedApplesis not a collection that contains objects, it’s an expression that creates a collection on the fly. That means that the changes that you do to the objects are discarded, and when you loopselectedApplesagain it will be recreated from scratch.Make it a collection using the
ToListmethod: