How to cast property of IEnumerable<DirectoryInfo> to List<string>

醉酒当歌 提交于 2020-04-17 22:41:23

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!