LINQ嵌套列表理解从多个文件夹中获取文件

时间:2013-03-06 16:10:58

标签: c# linq

我正在尝试从多个文件夹中获取.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个文件。{/ p>

谢谢

4 个答案:

答案 0 :(得分:6)

尝试以下

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));

答案 1 :(得分:3)

您可以使用接受搜索模式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个实例,这也是您想要的。

答案 2 :(得分:1)

试试这个

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

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

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

答案 3 :(得分:0)

替代易受攻击的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 - 误读问题,错过了“从一组目录”部分;我的耻辱是无法估量的。 :)