递归函数 - 如果为空则不要显示目录

时间:2014-04-15 07:25:13

标签: c# recursion

我正在创建一个需要列出特定文件夹中所有文件和目录的Web应用程序。 我创建了resurvice函数来列出这些,但另一个规范是,如果目录没有文件,那么不应该显示该目录。

现在的问题是,如果我有一个带子菜单的目录,带子菜单,子菜单,子菜单,只有最后一个子菜单中有文件,该怎么办?它仍然需要显示所有其他目录。

我不知道如何实现这一点,任何代码或提示都会受到赞赏!

我目前的递归函数:

private List<FolderModel> GetFolderSubFolders(IFolderInfo folder)
    {
        var retval = new List<FolderModel>();

        // Foreach subfolder in the given folder
        foreach (var subFolder in FolderManager.Instance.GetFolders(folder))
        {
                // Create new foldermodel
                var folderModel = new FolderModel
                {
                    FolderName = subFolder.FolderName,
                    Bestanden = GetFolderBestanden(subFolder),
                    // Recall this function
                    SubFolders = GetFolderSubFolders(subFolder)
                };

            // Check if we have files and subfolders
            if (folderModel.Bestanden.Any() && folderModel.SubFolders.Any())
            {
                folderModel.hasFilesAndFolders = true;
            }

            retval.Add(folderModel);

        }
        return retval;
    }

2 个答案:

答案 0 :(得分:0)

让它找到所有目录,然后过滤掉里面有文件的目录:

List<FolderModel> allFolders = GetFolderSubFolders(myFolder);

List<FolderModel> nonEmptyFolders = allFolders.Where(f => f.HasFiles).ToList();

答案 1 :(得分:0)

我没有尝试过这个,但我认为这样的事情应该有效:

private List<FolderModel> GetFolderSubFolders(IFolderInfo folder)
{
    var retval = new List<FolderModel>();

    // Foreach subfolder in the given folder
    foreach (var subFolder in FolderManager.Instance.GetFolders(folder))
    {
        // Recall this function
        List<FolderModel> subFolders = GetFolderSubFolders(subFolder);
        // I am assuming that "Bestanden" is also a List<T> and contains
        // the files of this folder
        List<Something> bestanden = GetFolderBestanden(subFolder);
        // Don't do anything if an empty list was returned
        if(subFolders.Count > 0 || bestanden.Count > 0)
        {
            // Create new foldermodel
            var folderModel = new FolderModel
            {
                FolderName = subFolder.FolderName,
                Bestanden = bestanden,
                SubFolders = subFolders
            };

            // Check if we have files and subfolders
            if (folderModel.Bestanden.Any() && folderModel.SubFolders.Any())
            {
                folderModel.hasFilesAndFolders = true;
            }

            retval.Add(folderModel);
        }
    }
    // If nothing was found this will return an empty list
    return retval;
}

这个想法是,如果你在最后一级找不到任何东西,你就不会返回任何东西。以上可能不起作用,因为我没有运行它,但你可能会得到一个提示。