Alternative way to extract the most recent file using LINQ All, I have written some code to get the latest files from a directory, the files I am looking for contain the string sProcScript = "sProcScript" and in the selected directory I might have several versions:

sProcScriptBigGuns1001.sql
sProcScriptBigGuns1007.sql
sProcScriptEdAggVal1006.sql
sProcScriptEdAggVal1007.sql
...


and I want to pick up the latest version only (the version number being the number after the file name i.e. 1007 etc.). So in the above this would be sProcScriptBigGuns1007.sql and sProcScriptEdAggVal1007.sql. To do this I wrote the following snippet (as part of a larger method), where strPath is the path to the relevant directory

DirectoryInfo dirInfo = new DirectoryInfo(strPath);
List&lt;FileInfo&gt; listFileInfo = new List&lt;FileInfo&gt;();
listFileInfo = dirInfo.EnumerateFiles().ToList&lt;FileInfo&gt;();

// Loop in to locate special processes.
List&lt;FileInfo&gt; specialProcList = new List&lt;FileInfo&gt;();
foreach (FileInfo fi in listFileInfo)
    if (Path.GetFileNameWithoutExtension(fi.FullName).Contains(sProcScript))
        specialProcList.Add(fi);

// Get distinct.
List&lt;string&gt; nameList = new List&lt;string&gt;();
foreach (FileInfo fi in specialProcList)
{
    string strsProc = 
        Path.GetFileNameWithoutExtension(Regex.Replace(fi.Name, @"[\d]", String.Empty));
    if (!nameList.Contains(strsProc))
        nameList.Add(strsProc);
}
List&lt;FileInfo&gt; tmpList;
List&lt;string&gt; tmpNameList = new List&lt;string&gt;();
tmpList = specialProcList.OrderByDescending(f =&gt; f.Name).ToList();
foreach (string name in nameList)
{
    foreach (FileInfo fi in tmpList)
    {
        if (fi.Name.Contains(name))
        {
            tmpNameList.Add(fi.Name);
            listFilesFound.Add(fi);
            break;
        }
    }
}


which works great. However, I think there will be a much better and neater way of doing this using LINQ but I am new to LINQ and can't seem to get started with it (the attempts I have made are poor enough to not want to post them here!). Can someone demonstate a better way of doing the above operation using LINQ?

Thanks for your time.
This should do it:

var selectedFileInfos = listFileInfo
    .Where(x =&gt; { 
        var filename = Path.GetFileNameWithoutExtension(x.FullName); 
        return specialProcList.Any(y =&gt; filename.Contains(y);})
    .OrderByDescending(x =&gt; x.Name)
    .GroupBy(x =&gt; Path.GetFileNameWithoutExtension(Regex.Replace(x.Name, @"[\d]", String.Empty)) 
    .Select(x =&gt; x.First());


But be careful: file numbers should be padded with zeros. 0001, 0900, 0999, 1000, 1001. If they are just normally numbered with 1, 900, 999, 1000 etc., even your code will fail.