How to use LINQ to return a substring in FileInfo.Name

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

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);
}

The end result will be something similar to the following:

IList<string> fileNameSubstringValues = files.LINQ-QUERY-HERE;
+4
source share
4 answers

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();
+6
source
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 =)

+2
source

FileInfo s, List<FileInfo>, , , 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 #, , , Select. Linq PLinq .

+2

FYI,

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 - ).

+1

All Articles