How to flatten nested objects with linq expression
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Flattening nested objects in C# means converting a hierarchy of collections into a single flat sequence. LINQ's SelectMany is the primary tool for this — it projects each element to a collection and then flattens all the collections into one sequence. For deeper nesting, chain multiple SelectMany calls. For tree structures with arbitrary depth, use recursive methods combined with LINQ.
SelectMany — Basic Flattening
SelectMany with Result Selector
Include parent information alongside child elements:
Query Syntax (from ... from)
Flattening Nested Collections
Three Levels Deep
Recursive Flattening (Tree Structures)
For tree structures with arbitrary depth:
Flattening with Index
Flattening Dictionaries
Common Pitfalls
- Null child collections: If
dept.Employeesisnull,SelectManythrowsNullReferenceException. Usedept.Employees ?? Enumerable.Empty<Employee>()or initialize collections in constructors. - Confusing
SelectandSelectMany:Select(d => d.Employees)returnsIEnumerable<List<Employee>>(nested).SelectMany(d => d.Employees)returnsIEnumerable<Employee>(flat). UseSelectManyfor flattening. - Deferred execution:
SelectManyis lazily evaluated. If the source collection changes before you enumerate the result, you get the updated data. Call.ToList()to materialize if you need a snapshot. - Stack overflow with deep recursion: Recursive
Flatten()on very deep trees can overflow the stack. For trees deeper than ~1000 levels, use an iterative approach with an explicitStack<T>. - Losing parent context: Plain
SelectMany(d => d.Employees)loses the department information. Use the overload with a result selectorSelectMany(d => d.Employees, (d, e) => new { d.Name, e })to keep parent data.
Summary
- Use
SelectManyto flatten one level of nested collections into a single sequence - Chain multiple
SelectManycalls for deeper nesting (Company → Department → Employee) - Use the result selector overload to preserve parent context in flattened results
- For tree structures with arbitrary depth, use recursive methods with
ConcatandSelectMany - Always handle null child collections to prevent
NullReferenceExceptioninSelectMany
Related reading
- How to flatten tree via LINQ?
- 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 force LINQ Sum to return 0 while source collection is empty
- How to generate async version of wcf functions without service reference?
- How to Generate Combinations of Elements of a ListT in .NET 4.0
- How to generate .NET 4.0 classes from xsd?
- How to get a MemoryStream from a Stream in .NET?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.