Can someone tell me what I'm doing wrong with the following Linq query? I'm 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>
                You're trying to access dirs as if it were an array or a list. It's just an IEnumerable<T>. Try this:
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
Note that I haven't used a query expression here because it seems pretty pointless for just a single clause. You could put it all into one statement, too:
var first = currentDirectory.GetDirectories()
                            .OrderByDescending(eachDir => eachDir.FullName)
                            .FirstOrDefault();
                        If you didn't use var, the reason for the error would be more clear.
    IEnumerable<DirectoryInfo> dirs = from eachDir in diList 
               orderby eachDir.FullName descending                     
               select eachDir; 
    MessageBox.Show(dirs[0].FullName);
                        This is simply a case of not reading the error message.
The code does not compile, and produces this error message:
Cannot apply indexing with [] to an expression of type 'System.Linq.IOrderedEnumerable<System.IO.DirectoryInfo>'
In other words, the [..] part does not work with a enumerable, which is the result of using a Linq query.
You have multiple choices, but here are two:
I think the first method is a poor choice, so here is how the code looks 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);
                        use
    DirectoryInfo[] diList = currentDirectory.GetDirectories();
    var dir = (from eachDir in diList
               orderby eachDir.FullName descending                    
               select eachDir).FirstOrDefault();
    if (dir != null)
    MessageBox.Show(dir.FullName);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With