【问题标题】:How to use LINQ to return substring of FileInfo.Name如何使用 LINQ 返回 FileInfo.Name 的子字符串
【发布时间】:2009-01-06 21:13:39
【问题描述】:

我想将下面的“foreach”语句转换为 LINQ 查询,将文件名的子字符串返回到列表中:

IList<string> fileNameSubstringValues = new List<string>();

//Find all assemblies with mapping files.
ICollection<FileInfo> files = codeToGetFileListGoesHere;

//Parse the file name to get the assembly name.
foreach (FileInfo file in files)
{
    string fileName = file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")));
    fileNameSubstringValues.Add(fileName);
}

最终结果将类似于以下内容:

IList<string> fileNameSubstringValues = files.LINQ-QUERY-HERE;

【问题讨论】:

  • 这里没有查询,只是从A[]到B[]的转换。

标签: c# .net linq


【解决方案1】:

试试这样的:

var fileList = files.Select(file =>
                            file.Name.Substring(0, file.Name.Length -
                            (file.Name.Length - file.Name.IndexOf(".config.xml"))))
                     .ToList();

【讨论】:

  • 投票赞成:我更喜欢扩展方法语法而不是这里的查询语法,因为实际上没有查询:您的目标是对所有元素执行转换。没有 'where' 或 'orderby' 或交叉 'select' 甚至 'select new { x, y }。
  • @Jay,我也更喜欢简单投影的扩展方法语法,查询语法我想我只在做连接时使用它...
  • 更好,因为 1) 流畅的界面 2) 查询不需要括号
【解决方案2】:
IList<string> fileNameSubstringValues =
  (
    from 
      file in codeToGetFileListGoesHere
    select 
      file.Name.
        Substring(0, file.Name.Length - 
          (file.Name.Length - file.Name.IndexOf(".config.xml"))).ToList();

享受 =)

【讨论】:

    【解决方案3】:

    如果你碰巧知道FileInfos 集合的类型,并且是List&lt;FileInfo&gt;,我可能会跳过Linq 并写:

            files.ConvertAll(
                file => file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
                );
    

    或者如果它是一个数组:

            Array.ConvertAll(
                files,
                file => file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
                );
    

    主要是因为我喜欢说“转换”而不是“选择”来向阅读此代码的程序员表达我的意图。

    但是,Linq 现在是 C# 的一部分,所以我认为坚持让阅读程序员了解 Select 的作用是完全合理的。 Linq 方法让您在未来轻松迁移到 Plinq。

    【讨论】:

      【解决方案4】:

      仅供参考,

      file.Name.Substring(0, file.Name.Length - (file.Name.Length - file.Name.IndexOf(".config.xml")))
      

      一样
      file.Name.Substring(0, file.Name.IndexOf(".config.xml"));
      

      此外,如果该字符串“.config.xml”出现在文件名末尾之前,您的代码可能会返回错误的内容;您可能应该将 IndexOf 更改为 LastIndexOf 并检查返回的索引位置 + 11(字符串的大小)== 文件名的长度(假设您正在寻找以 .config.xml 结尾的文件而不仅仅是带有 .config 的文件.xml 出现在名称中的某处)。

      【讨论】:

        猜你喜欢
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        • 2012-10-22
        • 2013-09-30
        • 2013-11-18
        • 1970-01-01
        • 2016-08-27
        • 1970-01-01
        相关资源
        最近更新 更多