有人可以告诉我以下 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/