如何转换IEnumerable< DirectoryInfo>的属性;列出< string> [英] How to cast property of IEnumerable<DirectoryInfo> to List<string>

查看:62
本文介绍了如何转换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();

这篇关于如何转换IEnumerable&lt; DirectoryInfo&gt;的属性;列出&lt; string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆