Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good lambda expression or better way to reduce for each loop

Tags:

c#

.net

I want to get sub folders of a root folder. And i am able to get it through the below code. But has a issue when the sub folder has a sub folder in it and i over come it writing a second for each loop. But what if the second sub folder has a sub folder under it. So there will be an infinte for each loop, so i have to overcome it. Any help is worthfull.Thanks in advance.

foreach (Folder.Folder folder in FolderService.Instance.GetSubFolders(userContext, folderID))
            {
                folderById.Add(folder.FolderID, folder);
                foreach (Folder.Folder sfolder in FolderService.Instance.GetSubFolders(userContext, folder.FolderID))
                {
                    folderById.Add(sfolder.FolderID, sfolder);
                }
            }
like image 521
Malcolm Avatar asked Dec 22 '22 05:12

Malcolm


1 Answers

Perfect place for recursion:

... TraverseFolder(rootFolderID, userContext)
{
    var folderById = new ...;
    TraverseFolder(folderById, rootFolderID, userContext);

    return folderById;
}

void TraverseFolder(folderById, folderID, userContext)
{
    var folders = FolderService.Instance.GetSubFolders(userContext, folderID);
    foreach(var folder in folders)
    {
        folderById.Add(folder.FolderID, folder);
        TraverseFolder(folder.FolderID);
    }
}

Theoretically, you can have recursive lambdas, but they are waay too complicated.

like image 126
Anton Gogolev Avatar answered Mar 27 '23 00:03

Anton Gogolev