问题
I'm running the following code to enumerate all the available folders and subfolders on a network share,
DirectoryInfo dirInfo = new DirectoryInfo(path);
var dirList = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories);
foreach (var d in dirList)
{
Console.WriteLine(d.FullName);
}
The code itself works absolutely fine. However, rather than declare the var dirList
, I'd like to use a List<string>
variable directly, but it's not clear to me how to do this.
回答1:
This will extract the FullName from the sequence returned by EnumerateDirectories
DirectoryInfo dirInfo = new DirectoryInfo(@"path");
List<string> directories = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories)
.Select(x => x.FullName).ToList();
The Select method will return an IEnumerable and you can easily convert it to a List with the ToList extension.
However you could get the same result avoiding the DirectoryInfo class with the simpler Directory class (still ToList is required to operate on the sequence returned)
List<string> directories = Directory.EnumerateDirectories(path,"*.*", SearchOption.AllDirectories).ToList();
回答2:
You might want to check out Linq for example:
var dirList = dirInfo.EnumerateDirectories("*.", SearchOption.AllDirectories).Select(dir => dir.FullName).ToList();
来源:https://stackoverflow.com/questions/61173046/how-to-cast-property-of-ienumerabledirectoryinfo-to-liststring