Andrea Merlin
Andrea Merlin

Reputation: 31

Directory and subdirectory Filter in Linq

I need to list all directories from a path. I need to get only last subdirectory path and not all paths.

i.e. for

pathbase/2016/01

I don't need pathbase/2016 but pathbase/2016/01

Now I'm using this code:

List<string> dirs = new List<string>(Directory.EnumerateDirectories(pathBase));
string[] entries = System.IO.Directory.GetDirectories(pathBase, "*", 
    SearchOption.AllDirectories);

var listDir = from dir
              in entries

return listDir.ToList();

What type of filter can i use in Linq to exclude this directory?

Thanks.

Upvotes: 0

Views: 2274

Answers (1)

Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

Do you mean you need all leafs directories (directories that don't have subdirectories)?

If so this should do it

// First off, don't use GetDirectories on the static Directory class, it returns a string path and not a DirectoryInfo which isn't very usefull here, instead create a DirectoryInfo and go from there:

var RootDirectory = new DirectoryInfo(pathBase);
// Then queries all of it's subdirectories and filter on those
var listDir  = RootDirectory.GetDirectories("*",SearchOption.AllDirectories)
    .Where(dir=>!dir.GetDirectories().Any())
    .ToList();

Upvotes: 5

Related Questions