Writing LINQ queries against recursive elements (like TreeNode for example) is not straightforward. To highlight it, let’s consider an example where you want to retrieve all checked nodes of a TreeView. You can always implement it without LINQ but with the cost of reinventing the wheel each time you are browsing  recursive elements.

Fortunately LINQ can help on such scenario and that’s why the recursive Where extension has been designed for. It consists of an overload of the Where extension where you can specify, via a selector parameter, the recursive property of the recursive elements. As example the previous scenario is implemented with the following LINQ query:

var checkedNodes = tree.Nodes.Cast<TreeNode>().Where(n => n.Checked, n => n.ChildNodes.Cast<TreeNode>());

Note that circular references are not supported.

Last edited Jan 9, 2012 at 9:02 PM by odanvin, version 2


No comments yet.