c# - 如何从结构列表中有效地选择与给定模式匹配的所有值?

标签 c# linq struct

我有一个包含文件扩展名和 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/

相关文章:

c# - .Net Core/ASP5 应用程序的构建路径是什么?

c# - Windows 服务 Webbrowser 对象无效转换异常错误

c# - 通过C#在Excel中给出数字格式

c# - 在C#中将二维数组转换为字符串,寻找最优雅的方式

c++ - 在 vector 结构中显示 vector 结构

delphi - Delphi 中 CONTAINING_RECORD C 宏的等效函数是什么?

c - struct name 是一个指针吗?

c# - 在测试初始化​​方法中模拟 HttpContext.Current

c# - LINQ .ToList() 在单个结果上失败

c# - 为什么 IReadOnlyCollection 有 ElementAt 但没有 IndexOf