如何筛选Directory.EnumerateFiles多个标准是什么? [英] How to filter Directory.EnumerateFiles with multiple criteria?

查看:860
本文介绍了如何筛选Directory.EnumerateFiles多个标准是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

List<string> result = new List<string>();

foreach (string file in Directory.EnumerateFiles(path,"*.*",  
      SearchOption.AllDirectories)
      .Where(s => s.EndsWith(".mp3") || s.EndsWith(".wma")))
       {
          result.Add(file);                 
       }

它工作正常,然后做了我所需要的。除了一小的事情。我想找到一个更好的方法来对多个扩展名进行筛选。我想用一个字符串数组,过滤器,如这样的:

It works fine and does what I need. Except for one small thing. I would like to find a better way to filter on multiple extensions. I would like to use a string array with filters such as this:

string[] extensions = { "*.mp3", "*.wma", "*.mp4", "*.wav" };

什么是最有效的方式使用.NET框架4.0 / LINQ做到这一点?有什么建议?

What is the most efficient way to do this using NET Framework 4.0/LINQ? Any suggestions?

我倒是AP preciate任何帮助,是一个偶然的程序员: - )

I'd appreciate any help being an occasional programmer :-)

推荐答案

我创造了一些辅助的方法来解决这个问题,我的博客有关今年早些时候。

I created some helper methods to solve this which I blogged about earlier this year.

一个版本需要一个正则表达式 \ MP3。| \ .MP4 ,而另一个字符串列表,并运行在平行

One version takes a regex pattern \.mp3|\.mp4, and the other a string list and runs in parallel.

public static class MyDirectory
{   // Regex version
   public static IEnumerable<string> GetFiles(string path, 
                       string searchPatternExpression = "",
                       SearchOption searchOption = SearchOption.TopDirectoryOnly)
   {
      Regex reSearchPattern = new Regex(searchPatternExpression, RegexOptions.IgnoreCase);
      return Directory.EnumerateFiles(path, "*", searchOption)
                      .Where(file =>
                               reSearchPattern.IsMatch(Path.GetExtension(file)));
   }

   // Takes same patterns, and executes in parallel
   public static IEnumerable<string> GetFiles(string path, 
                       string[] searchPatterns, 
                       SearchOption searchOption = SearchOption.TopDirectoryOnly)
   {
      return searchPatterns.AsParallel()
             .SelectMany(searchPattern => 
                    Directory.EnumerateFiles(path, searchPattern, searchOption));
   }
}

这篇关于如何筛选Directory.EnumerateFiles多个标准是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆