【问题标题】:How can I Get rid of the Forward slashes " \\ " in an IEnumerable List如何摆脱 IEnumerable 列表中的正斜杠“\\”
【发布时间】:2019-09-16 07:11:56
【问题描述】:

我有如下定义的两个列表

IEnumerable<string> fileNames = new DirectoryInfo(Path)
  .EnumerateFiles("fileServer.config", SearchOption.AllDirectories)
  .Select(fi => fi.DirectoryName)
  .Select(dirPath => dirPath.Substring(Path.Length));


List<string> subFolderNames = fileNames.ToList();

但是这个 subFolderNames 的输出带有一个 \\ infront 每个元素,像这样

\\ElementName

我怎样才能摆脱这个\\

【问题讨论】:

    标签: c# list ienumerable


    【解决方案1】:

    从技术上讲,您可以Trim 不需要的字符(它们是目录分隔符):

       ...
       .Select(dirPath => dirPath
          .Substring(Path.Length)
          .TrimStart(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)); 
    

    或更改Substring 参数:

       ...
       .Select(dirPath => dirPath.Substring(Path.Length + 1));
    

    但是,如果你想要最里面的目录名

       IEnumerable<string> fileNames = new DirectoryInfo(Path)
         .EnumerateFiles("fileServer.config", SearchOption.AllDirectories)
         .Select(fi => fi.Name);
    

    【讨论】:

    • #1 是最漂亮的解决方案
    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 2022-01-09
    • 2013-07-03
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2015-10-08
    • 2020-08-18
    相关资源
    最近更新 更多