I would do this using recursion
void ProcessLevels(IEnumerable<Level> levels, int parentID, int levelNum)
{
foreach (var subLevel in levels.Where(l => l.PARENTID == parentID))
{
//print Level levelNum
//use logic to format according to the specific level if desired
ProcessLevels(levels, subLevel.ROOTID, levelNum + 1);
}
}
You can just call it then using
ProcessLevels(levels, 0, 1);
This has the advantage that if you ever have levels deeper than just 3-deep, it will continue to process down the chain. You could also limit it at 3 levels (or whatever you chose) by doing something like:
void ProcessLevels(IEnumerable<Level> levels, int parentID, int levelNum, int levelsDeep)
{
foreach (var subLevel in levels.Where(l => l.PARENTID == parentID))
{
//print Level levelNum
//use logic to format according to the specific level if desired
if (levelsLeft > 0)
{
ProcessLevels(levels, subLevel.ROOTID, levelNum + 1, levelsDeep - 1);
}
}
}
And make your call like:
ProcessLevels(levels, 0, 1, 3);