c# - 使用 Linq 检查 C# 中的目录

标签 c# linq

有人可以告诉我以下 Linq 查询有什么问题吗?我试图找到具有最高非数字值的目录。

        DirectoryInfo[] diList = currentDirectory.GetDirectories();

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

编辑:

以上代码编译不通过,编译器产生的错误是:

Cannot apply indexing with [] to an expression of type 'System.Linq.IOrderedEnumerable<System.IO.DirectoryInfo>

最佳答案

您正在尝试访问 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

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

var first = currentDirectory.GetDirectories()
                            .OrderByDescending(eachDir => eachDir.FullName)
                            .FirstOrDefault();

关于c# - 使用 Linq 检查 C# 中的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3014280/

相关文章:

c# - Linq 查询基于多个字段查找重复对象且属性为空

c# - 如何将 OrderBy 添加到此 LINQ 语句?

c# - Linq to SQl,从多个表中选择相同的列

c# - 使用 Linq 分区

c# - 在 .net web api 属性路由中的 Controller 级别使用 Route 而不是 RoutePrefix

c# - WPF C# DynamicDataDisplay - 更改 DateTimeAxis 颜色

c# - 笛卡尔积或 2 个大文本文件的最佳方法

c# - QueryOver 集合包含所有值

c# - 如何使用动态 javascript 下拉列表进行 MVC 编辑

c# - 使用 await 从 linq 语句中选择