2011-09-03 27 views
49

我在我的數據庫中有一個字段包含DateTime ?.我想對結果進行排序,這樣的NULL在上面顯示出來,然後通過日期時間遞減,例如,Linq OrderByDescending,null first

null 
null 
2012-04-01 
2012-01-01 
2011-09-04 

的原因是,我在看的到期日期,但有些項目不會過期。

+0

我發現這是一個更好的解決方案,如果它不是一個日期時間的http:// stackoverflow.com/a/15247558/59508 – kiev

回答

125

您可以從排序表達式返回DateTime.MaxValue而不是null,所以用null日期的行會先被排序:

yourData.OrderByDescending(row => row.dateTimeField ?? DateTime.MaxValue); 
+0

偉大的解決方案。 –

2

你可以嘗試這樣的事:

var nulls = table.Where(x => x.NullableDateTimeField == null); 
var notNulls = table.Where(x => x.NullableDateTimeField != null); 

var result = nulls.Concat(notNulls.OrderByDescending(x => x.NullableDateTimeField)); 

它比「可能是超高效」「顯然是正確」,但它的至少一個起點。

+0

您錯過了任何訂購條款。 –

25

我發現最簡單的方法是:

data.OrderBy(Function(o) o.myDate IsNot Nothing).ThenByDescending(Function(o) o.myDate) 
在C#

我認爲...

data.OrderBy(o => o.myDate != null).ThenByDescending(o => o.myDate) 

這也適用於LINQ to SQL。我不確定if(nullable, value)是否會成功轉換爲SQL。

0

David Oesterreich's blog:

var queryResult = 
orderedProducts from enumerableProducts 
order by orderedProducts.ProductName, 
orderedProducts.Price != null ? 1 : 0 descending, 
orderedProducts.Price 
select orderedProducts; 
1

看看喜歡接受的版本之上,但與語法C#V6

tickets.OrderByDescending(x => x?.Erstellt ?? DateTime.Now) 
+1

我可以請您請您在答案中添加更多的上下文。僅有代碼的答案很難理解。如果您可以在帖子中添加更多信息,它可以幫助提問者和未來的讀者。 – RBT

相關問題