【发布时间】:2016-05-26 13:15:34
【问题描述】:
我有一些功能允许用户在多个目录中搜索某种类型的文件,然后只将这些文件的路径添加到listbox。现在它是通过一些嵌套的foreach 语句完成的。它将检索数十万个文件路径,所以我很好奇还有什么其他有效的方法可以解决这个问题?
另外,我知道将这么多项目添加到listbox 听起来很愚蠢。我只是在做我被告知要做的事情。我有一种感觉,将来它会被要求删除,但文件路径仍然必须存储在某个地方的列表中。
注意:我使用WindowsAPICodePack 来获得一个允许选择多个目录的对话框。
List<string> selectedDirectories = new List<string>();
/// <summary>
/// Adds the paths of the directories chosen by the user into a list
/// </summary>
public void AddFilesToList()
{
selectedDirectories.Clear(); //make sure list is empty
var dlg = new CommonOpenFileDialog();
dlg.IsFolderPicker = true;
dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = true;
dlg.ShowPlacesList = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
selectedDirectories = dlg.FileNames.ToList(); //add paths of selected directories to list
}
}
/// <summary>
/// Populates a listbox with all the filepaths of the selected type of file the user has chosen
/// </summary>
public void PopulateListBox()
{
foreach (string directoryPath in selectedDirectories) //for each directory in list
{
foreach (string ext in (dynamic)ImageCB.SelectedValue) //for each file type selected in dropdown
{
foreach (string imagePath in Directory.GetFiles(directoryPath, ext, SearchOption.AllDirectories)) //for each file in specified directory w/ specified format(s)
{
ListBox1.Items.Add(imagePath); //add file path to listbox
}
}
}
}
编辑:不确定是否有区别,但我使用的是WPF listbox,而不是winforms。
【问题讨论】:
-
一句话...Linq
-
.. 你要在列表框中添加“数十万个文件路径”吗?
-
是的,到目前为止,这就是我这样做的人想要的。将来它们可能不会显示在列表框中,但仍必须保存在某个列表中。
-
@DavidPine 之前没怎么用过 Linq,我会读一读。我确实在某处读到,它在引擎盖下执行与 foreach 循环相同的基本操作。
标签: c# wpf foreach nested-loops