Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LINQ to return substring of FileInfo.Name

Tags:

c#

.net

linq

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<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 would be something similar to the following:

IList<string> fileNameSubstringValues = files.LINQ-QUERY-HERE;
like image 895
shackett Avatar asked Dec 22 '22 13:12

shackett


2 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();
like image 90
Christian C. Salvadó Avatar answered Dec 25 '22 03:12

Christian C. Salvadó


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

like image 30
casperOne Avatar answered Dec 25 '22 02:12

casperOne