[英]What is wrong with the following LINQ query?
I have been trying to dive into more advanced features of C# like LINQ and Lambda expressions, so I am a complete beginner when it comes to LINQ ans Lambda expressions. 我一直在尝试深入学习C#的更高级功能,例如LINQ和Lambda表达式,因此,对于LINQ ans Lambda表达式,我是一个完整的初学者。
My problem is that I have a list of paths of files contained on my computer and want to sort them based on the "last access time". 我的问题是我有计算机上包含的文件路径列表,并希望根据“上次访问时间”对它们进行排序。 To do this I wrote the following
为此,我写了以下内容
TempList = FilesList.OrderByDescending((FileInfo Files,string n) => { Files = new FileInfo(n) ;
Files.LastAccessTime ; } ) ;
FilesList
contains the paths of files in various orders. FilesList
包含各种顺序的文件路径。 FilesList
is of type list<string>
and TempList
is of type IEnumerable<string>
. FilesList
的类型为list<string>
而TempList
的类型为IEnumerable<string>
。
To this query compiler is generating the following error: 为此查询,编译器生成以下错误:
The type arguments for method 'System.Linq.Enumerable.OrderByDescending<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Can someone please point out what is wrong with my query. 有人可以指出我的查询出了什么问题吗? I am unable to understand from the error message.
从错误消息中我无法理解。
Try this instead (assuming your list of "files" is actually a list of fully-qualified file names): 请尝试以下操作(假设您的“文件”列表实际上是完全限定的文件名列表):
TempList = FilesList.OrderByDescending(n => new FileInfo(n).LastAccessTime).ToList();
I can't promise the syntax is completely correct as I don't have a list of files to run it on. 我不能保证语法是完全正确的,因为我没有运行它的文件列表。 Also, there may be more efficient methods than instantiating a
FileInfo
object for each file. 同样,可能有比为每个文件实例化
FileInfo
对象更有效的方法。
First of all, there is no way to get FileInfo
parameter when FilesList
is List<string>
. 首先,当
FilesList
为List<string>
时, FilesList
获取FileInfo
参数。 You just get string. 您只是得到字符串。 Furthermore, you don't return anything from your lambda.
此外,您不会从lambda返回任何内容。 And you can't reassign lambda parameters either.
而且您也不能重新分配lambda参数。
TempList = FilesList.OrderByDescending(n => new FileInfo(n).LastAccessTime);
Or, if you want to use {}
within your lambda to make it multi-line lambda, you have to return
something somewhere in the code (most likely as the last statement): 或者,如果要在lambda中使用
{}
使其成为多行lambda,则必须在代码中的某处return
某些内容(最有可能作为最后一条语句):
TempList = FilesList.OrderByDescending(n => { var file = new FileInfo(n); return file.LastAccessTime });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.