tags:

views:

59

answers:

3

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.Please help in writing the LINQ Query.

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

Is this Correct?For example i 20 dll's startwith name "SAMPLE"

+6  A: 

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();
Darin Dimitrov
while am getting the file's am getting the duplicates also.How to remove the duplicates?
programmer4programming
var r = Directory .EnumerateFiles(@"c:\work", "SAMPLE*.dll", SearchOption.AllDirectories).Select(a => a.Filename).Distinct().ToList();*r* will contain a List<string> collection containing all filenames.
Michael
A: 

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();
Venemo
A: 

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));
Lee Sy En
Thanks one and all
programmer4programming