Check directories in C # with Linq

Can someone tell me what I'm doing wrong with the following Linq query? I am trying to find the directory with the highest aphanumerical value.

        DirectoryInfo[] diList = currentDirectory.GetDirectories();

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

EDIT:

The above code does not compile, the error that the compiler generates is:

Cannot apply indexing with [] to an expression of type 'System.Linq.IOrderedEnumerable<System.IO.DirectoryInfo>
+5
source share
4 answers

You are trying to access dirsas if it were an array or a list. It is simple IEnumerable<T>. Try the following:

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

Please note that I did not use the query expression here because it seems pretty pointless for just one sentence. You can also add all this to one statement:

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

var, .

    IEnumerable<DirectoryInfo> dirs = from eachDir in diList 
               orderby eachDir.FullName descending                     
               select eachDir; 
    MessageBox.Show(dirs[0].FullName);
+3

, .

:

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

, [..] , Linq.

, :

  • Convert to array and select first element
  • Use Linq Extension Method to Capture First

I think the first method is a bad choice, so here is what the code looks like with the second:

DirectoryInfo[] diList = currentDirectory.GetDirectories();

var dirs = from eachDir in diList
           orderby eachDir.FullName descending                    
           select eachDir;
var dir = dirs.FirstOrDefault();
if (dir != null)
    MessageBox.Show(dir.FullName);
+2
source

using

    DirectoryInfo[] diList = currentDirectory.GetDirectories();

    var dir = (from eachDir in diList
               orderby eachDir.FullName descending                    
               select eachDir).FirstOrDefault();
    if (dir != null)
    MessageBox.Show(dir.FullName);
+1
source

All Articles