2011-03-17 124 views
329

我相信這將是一個相對簡單的問題。LINQ Orderby降序查詢

我有一個LINQ查詢,我想按最近創​​建的日期排序。

參見:

 var itemList = from t in ctn.Items 
         where !t.Items && t.DeliverySelection 
         orderby t.Delivery.SubmissionDate descending 
         select t; 

我也曾嘗試:

 var itemList = (from t in ctn.Items 
         where !t.Items && t.DeliverySelection 
         select t).OrderByDescending(); 

但是這給出了一個錯誤:

沒有重載方法 'OrderByDescending' 取0參數

從我讀過的內容來看,我確信我做過的第一種方法應該可行。我試着改變下降到只是爲了看看它做了什麼,但它保持不變。

如果有人能看看查詢,看看我是否做錯了,我將不勝感激。謝謝:)

回答

511

你需要選擇一個屬性來排序,並把它作爲一個lambda表達式OrderByDescending

,如:

.OrderByDescending(x => x.Delivery.SubmissionDate); 

真的,雖然你的LINQ的第一個版本聲明應該工作。 t.Delivery.SubmissionDate實際上是否填充有效日期?

+0

嗨optus,謝謝你的答覆。我已經找出問題所在。我使用的是一個paginatedList,它實際上是從該輔助類中進行排序。一旦時間限制到達,我會將您的答案標記爲正確:) – 109221793 2011-03-17 20:40:46

23

我覺得第二個應該是

var itemList = (from t in ctn.Items 
       where !t.Items && t.DeliverySelection 
       select t).OrderByDescending(c => c.Delivery.SubmissionDate); 
+0

雙下降? – Snowbear 2011-03-17 20:31:47

+0

我認爲對他是公平的,我在發佈時輸入了錯誤的查詢(即,在第二個最後的命令行中),他可能只是複製並粘貼來演示使用Lambda OrderByDescending。 – 109221793 2011-03-17 20:49:43

+0

對不起。我是一個複製/粘貼錯誤。我會編輯它。 – Jonathan 2011-03-17 21:33:21

122

我想這首先失敗,因爲你點值是零。如果交付是一個外鍵關聯表,那麼你應該首先包括這個表,例如:

var itemList = from t in ctn.Items.Include(x=>x.Delivery) 
        where !t.Items && t.DeliverySelection 
        orderby t.Delivery.SubmissionDate descending 
        select t; 
+47

+1。我討厭那些沒有理由而沮喪的人。 – jp2code 2014-07-01 18:30:16

+0

包括相當於 DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith (i => i.Delivery); ctn.LoadOptions = dlo; – mrosiak 2015-02-17 16:52:32