简体   繁体   中英

Check Directories in C# using Linq

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:

  • Convert to an array, and pick the first element
  • Use the Linq extension method to grab the first

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM