1

私は IEnumerable<DirectoryInfo> を持っており、正規表現の配列を使用してフィルタリングして潜在的な一致を見つけたいと考えています。linq を使用してディレクトリと正規表現文字列を結合しようとしましたが、うまくいかないようです。これが私がやろうとしていることです...

string[] regexStrings = ... // some regex match code here.

// get all of the directories below some root that match my initial criteria.
var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories)
                  where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0
                        && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories
                            || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files)
                  select d;

// filter the list of all directories based on the strings in the regex array
var filteredDirs = from d in directories
                   join s in regexStrings on Regex.IsMatch(d.FullName, s)  // compiler doesn't like this line
                   select d;

...これを機能させる方法について何か提案はありますか?

4

3 に答える 3

4

すべての正規表現に一致するディレクトリのみが必要な場合。

var result = directories
    .Where(d => regexStrings.All(s => Regex.IsMatch(d.FullName, s)));

少なくとも 1 つの正規表現に一致するディレクトリのみが必要な場合。

var result = directories
    .Where(d => regexStrings.Any(s => Regex.IsMatch(d.FullName, s)));
于 2009-07-08T18:39:08.017 に答える
2

とにかく、あなたが取っているアプローチがまさにあなたが望むものだとは思いません。これにより、最初の一致で短絡するのではなく、すべての正規表現文字列に対して名前がチェックされます。さらに、ディレクトリが複数のパターンに一致した場合、ディレクトリが複製されます。

次のようなものが欲しいと思います:

string[] regexStrings = ... // some regex match code here.

// get all of the directories below some root that match my initial criteria.
var directories = from d in root.GetDirectories("*", SearchOption.AllDirectories)
                  where (d.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0
                        && (d.GetDirectories().Where(dd => (dd.Attributes & (FileAttributes.System | FileAttributes.Hidden)) == 0).Count() > 0// has directories
                            || d.GetFiles().Where(ff => (ff.Attributes & (FileAttributes.Hidden | FileAttributes.System)) == 0).Count() > 0) // has files)
                  select d;

// filter the list of all directories based on the strings in the regex array
var filteredDirs = directories.Where(d =>
    {
        foreach (string pattern in regexStrings)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(d.FullName, pattern))
            {
                return true;
            }
        }

        return false;
    });
于 2009-07-08T18:19:04.843 に答える
0

結合の前に Where キーワードがありません

于 2009-07-08T18:14:56.160 に答える