Reputation: 47
I'm trying to query a folder and return only folders with a numeric folder name. The catch is that I need it in a DirectoryInfo[]
object.
I could do it like this (and it works):
List<string> subDirList = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly)
.Where(f => Regex.IsMatch(f, @"[\\/]\d+$")).ToList();
But I really need something like this:
DirectoryInfo[] subDirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly)
.Where(f => Regex.IsMatch(f, @"[\\/]\d+$"));
Any suggestions?
Upvotes: 2
Views: 267
Reputation: 476750
You can use a .Select(..)
to map it to DirectoryInfo
and then use ToArray()
:
DirectoryInfo[] subDirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly)
.Where(f => Regex.IsMatch(f, @"[\\/]\d+$"))
.Select(x => new DirectoryInfo(x)) //convert it to a DirectoryInfo
.ToArray(); // make the result an Array
Upvotes: 5
Reputation: 23732
Instantiate an object of type DirectoryInfo
and then make your query. The method DirectoryInfo.GetDirectories will return the desired array of type DirectoryInfo
DirectoryInfo dirInfo = new DirectoryInfo(yourpath);
DirectoryInfo[] subDirs = dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)
.Where(f => Regex.IsMatch(f.FullName, @"[\\/]\d+$")).ToArray();
EDIT:
In C# 7 you could avoid using regex with a simple int.TryParse
:
DirectoryInfo[] subDirs = dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)
.Where(f => int.TryParse(f.Name, out _)).ToArray();
below C# 7 you would need an extra variable of type int
for the out
value
Upvotes: 2