How to use LINQ to return substring of FileInfo.Name

后端 未结 4 1086
遇见更好的自我
遇见更好的自我 2021-01-19 21:47

I would like to convert the below \"foreach\" statement to a LINQ query that returns a substring of the file name into a list:

IList fileNameSu         


        
相关标签:
4条回答
  • 2021-01-19 22:26

    If you happen to know the type of the collection of FileInfos, and it's a List<FileInfo>, I'd probably skip the Linq and write:

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

    or if it's an array:

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

    Mainly because I like saying "Convert" instead of "Select" to express my intent to a programmer reading this code.

    However, Linq is part of C# now, so I think it's perfectly reasonable to insist that a reading programmer understand what Select does. And the Linq approach lets you easily migrate to PLinq in the future.

    0 讨论(0)
  • 2021-01-19 22:29
    IList<string> fileNameSubstringValues =
      (
        from 
          file in codeToGetFileListGoesHere
        select 
          file.Name.
            Substring(0, file.Name.Length - 
              (file.Name.Length - file.Name.IndexOf(".config.xml"))).ToList();
    

    Enjoy =)

    0 讨论(0)
  • 2021-01-19 22:31

    Try something like this:

    var fileList = files.Select(file =>
                                file.Name.Substring(0, file.Name.Length -
                                (file.Name.Length - file.Name.IndexOf(".config.xml"))))
                         .ToList();
    
    0 讨论(0)
  • 2021-01-19 22:35

    FYI,

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

    is the same as

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

    Also, if that string ".config.xml" appears before the end of the file name, your code will probably return the wrong thing; You should probably change IndexOf to LastIndexOf and check that the index position returned + 11 (the size of the string) == length of the filename (assuming you're looking for files ending in .config.xml and not just files with .config.xml appearing somewhere in the name).

    0 讨论(0)
提交回复
热议问题