I have following code:
IEnumerable<TreeItem> rootTreeItems = BuildRootTreeItems();
BuildTreeView(rootTreeItems.ElementAt(0));
private static void BuildTreeView(TreeItem treeItem)
{
TreeItem subMenuTreeItem = new TreeItem();
subMenuTreeItem.Header = "1";
TreeItem subMenuTreeItem2 = new TreeItem();
subMenuTreeItem.Header = "2";
treeItem.TreeItems.Add(subMenuTreeItem);
treeItem.TreeItems.Add(subMenuTreeItem2);
}
The weird thing is after the BuildTreeView returns, the first element of rootTreeItems doesn’t have any children nodes, while it really has when debugging into the BuildTreeView method.
This problem really confused me for quite a long time, any one has any idea? thanks so much.
You’re most likely hitting a deferred execution issue with
IEnumerable<>. The thing to remember is that yourIEnumerable<TreeItem> rootTreeItemsis not a list, instead it is a promise to get a list each and every time it is asked to do so.So, if
BuildRootTreeItems()creates theIEnumerable<TreeItem>using a LINQ query and it doesn’t force the execution of the query using.ToList()or.ToArray()then each time that you userootTreeItemsyou are re-executing the query insideBuildRootTreeItems()Calling
rootTreeItems.ElementAt(0)will cause the query to execute. If later you try to callrootTreeItems.ElementAt(0)again then you are re-executing the query and getting back a different instance of the firstTreeItem.Try changing the first line like so:
This forces the execution and will prevent re-execution later. I’ll bet your problem goes away.