递归函数-Don';如果目录为空,则不显示
本文关键字:显示 -Don 如果 递归函数 | 更新日期: 2023-09-27 17:58:26
我正在创建一个web应用程序,该应用程序需要列出特定文件夹中的所有文件和目录。我创建了resvice函数来列出这些文件,但另一个规范是,如果目录没有文件,则不应显示该目录。
现在的问题是,如果我有一个目录,有一个子菜单,有一子菜单,有子菜单,只有最后一个子菜单中有文件,该怎么办?它仍然需要显示所有其他目录。
我不知道如何实现这一点,任何代码或提示都将不胜感激!
我当前的递归函数:
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;
}
只需让它找到所有目录,然后过滤里面有文件的目录:
List<FolderModel> allFolders = GetFolderSubFolders(myFolder);
List<FolderModel> nonEmptyFolders = allFolders.Where(f => f.HasFiles).ToList();
我没有试过运行这个,但我认为这样的东西应该可以工作:
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;
}
这个想法是,如果你在最后一级没有找到东西,你就不会返回任何东西。以上可能不起作用,因为我还没有运行它,但你可能会得到一个提示。