Linq 不处理字符串列表



我正在尝试从目录中获取包含文件路径的字符串列表。用户将以逗号分隔的格式指定文件扩展名,例如 "gif, jpg" 。这是我的代码。

private static List<string> GetFiles(string DirectoryPath, string Extensions)
        {
            List<string> FilePaths = new List<string>();
            if (Directory.Exists(DirectoryPath))
            {
                //Calling this line more than once is not allowed.
                List<string> AllFiles = Directory.EnumerateFiles(DirectoryPath, "*.*", SearchOption.AllDirectories).ToList();
                if (!string.IsNullOrEmpty(Extensions) && !string.IsNullOrWhiteSpace(Extensions))
                {
                    foreach (string Extension in Extensions.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        List<string> SearchedFiles = AllFiles.Where(f => f.EndsWith(Extension)).ToList();
                        FilePaths.AddRange(SearchedFiles);
                    }
                }
                else FilePaths.AddRange(AllFiles);
            }
            return FilePaths;
        }

代码工作正常,但它只检索第一个扩展的结果,而不检索下一个后续扩展的结果。它只是忽略在foreach循环内的第一行中指定的Linq,该循环初始化SearchedFiles等于具有0个结果的列表。我知道拆分功能似乎没有提供后续扩展,但它工作正常。此外,我尝试使用.指定扩展,但没有奏效。

注意:我不想多次在目录中搜索。

第二个扩展的开头和后面的任何内容(索引> 0)都有一个额外的空格。

只需修剪它:

f.EndsWith(Extension.Trim());

最新更新