How to flatten tree via LINQ?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Flattening a tree means turning hierarchical nodes into one sequence that can be filtered, projected, or searched with ordinary LINQ queries. The tricky part is that LINQ does not magically recurse on its own. You need a traversal method that walks each node and then emits its descendants in a predictable order.
Model the Tree Clearly
Assume each node has a value and a sequence of children. A simple class is enough for the examples:
Now imagine a tree such as a company hierarchy or category structure. The goal is to convert that nested shape into IEnumerable<Node> so you can use normal LINQ operations on it.
A Recursive LINQ-Friendly Flatten Method
The common approach is a recursive extension method. It returns each node, then recursively returns all descendants.
This method is generic, so it works with any tree-like model as long as you can tell it how to get a node's children.
Use it like this:
This produces a depth-first traversal in the same order the children are stored.
Why SelectMany Appears in Many Solutions
You will often see recursive LINQ solutions written with Concat and SelectMany. That style is compact and expresses the same idea.
This version is elegant, but the yield return version is often easier to debug and reason about. Both are valid. Choose the one your team will read comfortably.
Flatten Multiple Roots
Many real datasets are forests, not single trees. The earlier IEnumerable<T> extension already handles that case because it accepts a sequence of roots.
That means you can flatten:
- menu systems with several top-level entries
- organization charts with multiple departments
- file-like category groupings loaded from a database
Once flattened, ordinary LINQ becomes much easier:
This is the real payoff. Flatten first, then write simple queries against the flat sequence.
Watch for Deep Trees
Recursion is clear, but extremely deep trees can overflow the stack. If the data may be very deep, switch to an iterative traversal using an explicit Stack<T>.
This still gives you a depth-first walk, but without depending on the call stack.
Choose the Traversal Order Intentionally
Not every flattening problem wants the same order. The examples above are depth-first. If you need breadth-first traversal, use a queue instead of recursion or a stack.
The important design question is not "how do I use LINQ". It is "what order should the flattened sequence represent". Once that is clear, the code becomes straightforward.
Common Pitfalls
- Expecting plain
SelectManyto recurse automatically through all descendants. - Forgetting that recursive solutions can fail on very deep trees.
- Losing the intended node order by using an unsuitable traversal strategy.
- Writing a tree-specific helper when a generic
childrenSelectorversion would be reusable. - Flattening nodes when you really needed only leaf nodes or only descendants, not the root.
Summary
- Flattening a tree in LINQ requires an explicit traversal method.
- A generic recursive extension method is the most common solution.
- '
yield returnversions are often easier to maintain than heavily nested LINQ expressions.' - Use an iterative stack-based traversal when tree depth may be large.
- Decide on depth-first versus breadth-first order before writing the flatten logic.
Related reading
- How to for each the hashmap?
- How to generate a power set of a given set?
- How to Generate Combinations of Elements of a ListT in .NET 4.0
- How to generate maximally unbalanced AVL trees
- How to force a Solution file SLN to be opened in Visual Studio 2013?
- How to force C .net app to run only one instance in Windows?
- How to generate random graphs?
- How to generate the power-set of a given List?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.