如何转换IEnumerable< DirectoryInfo>的属性;列出< string>
我正在运行以下代码来枚举网络共享上所有可用的文件夹和子文件夹,
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);
}
代码本身可以正常工作.但是,我不想直接声明var dirList
,而是想直接使用List<string>
变量,但是我不清楚如何做到这一点.
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.
这将从EnumerateDirectories返回的序列中提取全名
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();
Select方法将返回一个IEnumerable,您可以轻松地将其转换为具有ToList扩展名的List.
The Select method will return an IEnumerable and you can easily convert it to a List with the ToList extension.
但是,避免使用更简单的Directory类避免使用DirectoryInfo类(仍然需要ToList才能对返回的序列进行操作),您可以获得相同的结果
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();