在分支目录中查找第一个文件

Find First File in a Branching Directory

我试图在目录树中找到第一个 .dcm,然后获取第一个完整路径 (a/a/a/123.dcm)。但是忽略找不到 ie .dcm 的目录。

示例:

a/a/a/123.dcm
a/a/a/1234.dcm
a/a/a/12345.dcm

a/a/b/23.dcm
a/a/b/234.dcm
a/a/b/2345.dcm

a/a/c/23.dcm
a/a/c/234.dcm
a/a/c/2345.dcm

答案应该是:a/a/a/123.dcma/a/b/23.dcma/a/c/23.dcm

我试过了:

var files = Directory.GetFiles(inputDir, "*.*", SearchOption.AllDirectories)
                         .Where(s => s.EndsWith(".dcm")).ToArray();
var dir = Directory.GetDirectories(inputDir, "*.*", SearchOption.AllDirectories).ToArray();

var biggest = files.First();

foreach (var item in dir)
{
   DirectoryInfo di = new DirectoryInfo(item);
   var q = from i in di.GetFiles("*.dcm", SearchOption.AllDirectories)
           select i.Name;
   var qq = q.First();

   foreach (var items in qq)
   {
      Console.WriteLine(items);
   }
}

但是我得到的是五个目录的答案。答案:

a/a/a/123.dcm
a/a/a/123.dcm
a/a/a/123.dcm
a/a/b/23.dcm 
a/a/c/23.dcm

我只是想知道是否有更简单的方法使用 LINQ 或其他方法来完成此操作?非常感谢你的帮助。干杯。

这是一个 LINQ 版本:

        var inputDir = @"c:\temp";

        var files = Directory
            .EnumerateFiles(inputDir, "*.dcm", SearchOption.AllDirectories)
            .Select(f => new FileInfo(f))
            .GroupBy(f => f.Directory.FullName, d => d, (d, f) => new { Directory = d, FirstFile = f.ToList().First() })
            .ToList();

        files.ForEach(f => Console.WriteLine("{0} {1}", f.Directory, f.FirstFile));