Found a c# head-scratcher. In the foreach loop, using the parent.Id property directly in a Enumerable.Where does not work. Putting it in a variable first works. There is no issue with directly accessing parent.Id in the Select statement.
List<Person> people = new List<Person>() {
new Person() { Id = 1, name = "John", parentId = null },
new Person() { Id = 2, name = "Sarah", parentId = null },
new Person() { Id = 3, name = "Daniel", parentId = 1 },
new Person() { Id = 4, name = "Peter", parentId = 1 }
};
List<object> peopleTree = new List<object>();
var parents = people.Where(p => !p.parentId.HasValue);
foreach (Person parent in parents)
{
int parentId = parent.Id;
var children = people
//.Where(p => p.parentId.Equals(parentId)) //This works, is able to find the children
.Where(p => p.parentId.Equals(parent.Id)) //This does not work, no children for John
.Select(p => new { Id = p.Id, Name = p.name, pId = parent.Id }); //pId set correctly
peopleTree.Add(new
{
Id = parent.Id,
Name = parent.name,
Children = children
});
}
Alternatively, if I use a for loop and put parent in a variable first, I can access the parent.Id property directly in the Where statement.
var parents = people.Where(p => !p.parentId.HasValue).ToArray();
for (int idx = 0; idx < parents.Count(); idx++)
{
var parent = parents[idx];
...
I could not find an answer to why it behaves like this. Can anyone explain it?