Pratik Singhal
Pratik Singhal

Reputation: 6492

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.
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 is of type list<string> and TempList is of type 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.

Upvotes: 0

Views: 872

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

First of all, there is no way to get FileInfo parameter when FilesList is List<string>. You just get string. Furthermore, you don't return anything from your lambda. And you can't reassign lambda parameters either.

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):

TempList = FilesList.OrderByDescending(n => { var file = new FileInfo(n); return file.LastAccessTime });

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66439

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.

Upvotes: 2

Related Questions