我一直在尝试深入研究C#的更高级功能,比如LINQ和Lambda表达式,所以当谈到LINQ和Lambda表达式时,我是一个完全的初学者。
我的问题是我有一个包含在我的计算机上的文件路径列表,并希望根据“上次访问时间”对它们进行排序。为此,我写了以下
TempList = FilesList.OrderByDescending((FileInfo Files,string n) => { Files = new FileInfo(n) ;
Files.LastAccessTime ; } ) ;
FilesList
包含各种订单中的文件路径。
FilesList
的类型为list<string>
TempList
的类型为IEnumerable<string>
。
对此查询编译器生成以下错误:
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.
有人可以指出我的查询有什么问题。我无法从错误消息中理解。
答案 0 :(得分:2)
请尝试这样做(假设您的“文件”列表实际上是一个完全限定的文件名列表):
TempList = FilesList.OrderByDescending(n => new FileInfo(n).LastAccessTime).ToList();
我不能保证语法完全正确,因为我没有要运行它的文件列表。此外,可能有比为每个文件实例化FileInfo
对象更有效的方法。
答案 1 :(得分:1)
首先,当FileInfo
为FilesList
时,无法获取List<string>
参数。你得到字符串。此外,你不会从你的lambda返回任何东西。而且你也不能重新分配lambda参数。
TempList = FilesList.OrderByDescending(n => new FileInfo(n).LastAccessTime);
或者,如果你想在你的lambda中使用{}
来使它成为多行lambda,你必须在代码中的某个地方return
(最有可能是最后一个语句):
TempList = FilesList.OrderByDescending(n => { var file = new FileInfo(n); return file.LastAccessTime });