2010-06-10 42 views
5

有人能告訴我我做錯了以下Linq查詢嗎?我試圖找到具有最高數值的目錄。查看C#中使用Linq的目錄

 DirectoryInfo[] diList = currentDirectory.GetDirectories(); 

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

編輯:

上面的代碼無法編譯,編譯器生成的錯誤是:

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

什麼是不工作呢? – 2010-06-10 12:31:25

+0

編譯器錯誤是不是告訴你問題是什麼? – 2010-06-10 12:32:41

+0

是的 - 對不起,我已經更新了相應的文章 – 2010-06-10 13:33:40

回答

10

你試圖訪問dirs就好像它是一個數組或一個名單。這只是一個IEnumerable<T>。試試這個:

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 

請注意,我沒有在這裏使用查詢表達式,因爲它對於單個子句似乎毫無意義。你可以把它所有到一個語句,也:

var first = currentDirectory.GetDirectories() 
          .OrderByDescending(eachDir => eachDir.FullName) 
          .FirstOrDefault(); 
1

使用

DirectoryInfo[] diList = currentDirectory.GetDirectories(); 

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

這簡直是不讀的錯誤消息的情況。

代碼不編譯,併產生此錯誤消息:

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

換句話說,所述[..]部分不與枚舉工作,這是使用的結果Linq查詢。

你有多種選擇,但這裏有兩個:

  • 轉換成一個陣列,並選擇第一要素
  • 使用LINQ的擴展方法搶得頭

我想第一種方法是一個不好的選擇,所以這裏是代碼與第二種方式的關係:

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

更多一個不理解錯誤信息的情況比不讀它 – 2010-06-10 13:59:26

3

如果您沒有使用var,錯誤的原因會更加清楚。

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

這正是我討厭'var'方法的原因,通過定義你的類型它只是更清晰, var關鍵字感覺像是一個巨大的倒退...... – Dal 2010-06-10 13:10:36

+0

不知道是否有某種方式讓編譯器在不涉及匿名類型時使用var來警告。 – 2010-06-10 13:59:25