使用Linq检查C#中的目录

Pau*_*els 5 c# linq

有人可以告诉我,我对以下Linq查询做错了吗?我正在尝试找到具有最高aphanumerical值的目录.

        DirectoryInfo[] diList = currentDirectory.GetDirectories();

        var dirs = from eachDir in diList
                   orderby eachDir.FullName descending                    
                   select eachDir;
        MessageBox.Show(dirs[0].FullName);
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的代码没有编译,编译器生成的错误是:

Cannot apply indexing with [] to an expression of type 'System.Linq.IOrderedEnumerable<System.IO.DirectoryInfo>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

您尝试访问dirs,就像它是一个数组或列表.这只是一个IEnumerable<T>.试试这个:

var dirs = diList.OrderByDescending(eachDir => eachDir.FullName);
var first = dirs.FirstOrDefault();
// Now first will be null if there are no directories, or the first one otherwise
Run Code Online (Sandbox Code Playgroud)

请注意,我没有在这里使用查询表达式,因为对于单个子句来说它似乎没有意义.您也可以将它全部放入一个语句中:

var first = currentDirectory.GetDirectories()
                            .OrderByDescending(eachDir => eachDir.FullName)
                            .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)