开发者

Writing the LINQ Query to search all the sub-directories?

I have a solution folder in which I have collect all the .dll's and store in a array list. I have to search all the sub-directories. How to write the LINQ Query?

var r = dir.GetFiles("*.dll")
           .Where<FileInfo>(i => i.Name.StartsWith("SAMPLE"))
           .ToList();

Is this Correct? For 开发者_JS百科example i 20 dll's startwith name "SAMPLE"


I would recommend you using the EnumerateFiles method:

var r = Directory
    .EnumerateFiles(@"c:\work", "*.dll", SearchOption.AllDirectories)
    .Where(file => file.StartsWith("SAMPLE"))
    .ToList();

or even better use the wildcard pattern to filter instead of filtering in-memory:

var r = Directory
    .EnumerateFiles(@"c:\work", "SAMPLE*.dll", SearchOption.AllDirectories)
    .ToList();


Yes, your LINQ is correct. It should work fine. Small correction: you don't need the tye parameter there. (The compiler can infer it.)

var list = dir.GetFiles("*.dll").Where(i => i.Name.StartsWith("SAMPLE")).ToList();


Yes it's correct.

I quickly created similar code to test myself and it works.

DirectoryInfo dir = new DirectoryInfo(@"C:\Test");
var files = dir.GetFiles("*.jpg").Where<FileInfo>(i => i.Name.StartsWith("Tet")).ToList();

files.ForEach(file => Console.WriteLine(file.Name));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜