LINQ嵌套列表推导从多个文件夹中获取文件

本文关键字:文件夹 获取 文件 嵌套 列表 LINQ | 更新日期: 2023-09-27 18:02:40

我正试图从多个文件夹中获取.mp3文件。

我已经可以通过下面的查询为一个文件夹设置了:

this.MusicList.ItemsSource =
                from string fileName in Directory.GetFiles(@"C:'Users'Public'Music'Sample Music")
                where System.IO.Path.GetExtension(fileName) == ".mp3"
                select new FileInfo(fileName);

对于目录列表还有其他方法吗?

这是我到目前为止所尝试的(没有返回结果):

var paths = new Dictionary<string, string> {
            {"default_music", @"C:'Users'Public'Music'Sample Music"},
            {"alternative_folder", @"C:'tmp"}
            };
this.MusicList.ItemsSource = 
from string fileName in (from string directoryName in paths.Values select Directory.GetFiles(directoryName))
where System.IO.Path.GetExtension(fileName) == ".mp3"
select new FileInfo(fileName);

from string directoryName in paths.Values select Directory.GetFiles(directoryName);返回一个{System.Linq.Enumerable.WhereSelectEnumerableIterator<string,string[]>},其中source字段包含我的路径,Result View包含我的.mp3文件。

谢谢

LINQ嵌套列表推导从多个文件夹中获取文件

试试下面的

this.MusicList.ItemsSource =
  from path in paths
  from fileName in Directory.GetFiles(path)
  where System.IO.Path.GetExtension(fileName) == ".mp3"
  select new FileInfo(fileName);

严格方法调用版本

this.MusicList.ItemSource = paths
  .SelectMany(path => Directory.GetFiles(path))
  .Where(fileName => System.IO.Path.GetExtension(fileName) == ".mp3")
  .Select(fileName => new FileInfo(fileName));

可以使用DirectoryInfo。EnumerateFiles方法,它接受搜索模式。因此,您不需要通过调用Path.GetExtension

来获取所有文件并对它们进行过滤。
var paths = new Dictionary<string, string> {
        {"default_music", @"C:'Users'Public'Music'Sample Music"},
        {"alternative_folder", @"C:'tmp"}
     };
MusicList.ItemsSource = paths.Values.Select(p => new DirectoryInfo(p))
                             .SelectMany(d => d.EnumerateFiles("*.mp3"));

DirectoryInfo.EnumerateFiles也返回FileInfo实例,这也是您想要的。

试试这个

Directory.EnumerateFiles(@"C:'Users'Public'Music'Sample Music", "*.mp3", SearchOption.AllDirectories)

返回.mp3的可枚举列表,您可以进一步筛选或枚举等。对于大量的文件和/或目录,这比GetFiles()更有效。

http://msdn.microsoft.com/en-us/library/dd383571.aspx

如果它是一个文件/目录,可替换为可靠的JaredPar:

var basePath = @"c:'temp";
var query = 
    from entry in Directory.EnumerateFileSystemEntries(basePath, "*.*", SearchOption.AllDirectories)
    let isDirectory = Directory.Exists(entry)
    let isFile = File.Exists(entry)
    select new { isDirectory, isFile, entry};
query.Dump();

编辑:Doh -误读问题,错过了"from a set of directories"部分;我的羞愧是无法估量的。:)