gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:57:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com