質問

What is the best way to handle this scenario

        foreach (var level1 in Levels.Where(l => l.PARENTID == 0))
        {
            // Print "LEVEL 1: Title"

            foreach (var level2 in Levels.Where(l => l.PARENTID == level1.ROOTID))
            {
                // Print "Level 2: Sub Title"

                foreach (var level3 in Levels.Where(l => l.PARENTID == level2.ROOTID))
                {
                    // Print "Level 3: Header"

                    ... etc ...
                }
            }
        }
役に立ちましたか?

解決

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);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top