我有一个包含文件扩展名和 bool 值(启用/禁用)的结构列表。
我想有效地从给定文件夹中选择与给定扩展名匹配的所有文件,其中扩展名设置为启用。 我在 StackOverflow 上发现了一个类似的问题: GetFiles with multiple extensions 但他们使用的是字符串数组,而不是结构。
结构:
public struct MusicFileExtension
{
public string name { get; set; }
public bool enabled { get; set; }
}
public List<MusicFileExtension> Extensions;
我能想到的唯一解决方案是:
private IEnumerable<FileInfo> getFilesInFolderByExtensions(Options options, DirectoryInfo folderPath, SearchOption searchSubfolders)
{
string [] ext = new string[options.Extensions.Count];
int i =0;
foreach (Options.MusicFileExtension extension in options.Extensions)
{
if (extension.enabled)
ext[i] = extension.name;
i++;
}
IEnumerable<FileInfo> files = folderPath.EnumerateFiles();
return files.Where(f => ext.Contains(f.Extension));
}
但是当可以选择使用 Linq 来使其更有效时,这就有点愚蠢了。
最佳答案
你是对的,您可以使用以下 LINQ 查询跳过准备步骤:
return files.Where(f => options.Extensions.Any(e => e.enabled && f.Extension == e.name));
存在 O(M*N)
,对于应用于非常大的目录的很长的扩展列表,此实现可能有些低效。在这种情况下,你最好构造一个 Set<string>
启用的扩展程序,如下所示:
ISet<string> enabled = new HashSet<string>(
options.Extensions.Where(e=>e.enabled).Select(e=>e.name)
);
IEnumerable<FileInfo> files = folderPath.EnumerateFiles();
return files.Where(f => enabled.Contains(f.Extension));
关于c# - 如何从结构列表中有效地选择与给定模式匹配的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431316/