今天

2010-10-12 68 views
2

LINQ的DateTimeOffset比較,我有一個的DateTimeOffset屬性的類:今天

public class Sample 
{ 
    public DateTimeOffset expires { get; set; } 
} 

,最終他們的集合:

IEnumerable<Sample> collection; 

2個問題:

  1. 創建一個返回所有Sampl的方法的最佳方法是什麼?到期時大於現在且仍然是今天(即,午夜之前)?

  2. 什麼是最好的方式來返回集合中的所有樣品項目,在未來24小時內到期?

回答

2
// greater than now, still today    
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.Date == DateTime.Today); 

// expires in the next 24 hours 
collection.Where(d => d.expires.DateTime > DateTime.Now && d.expires.DateTime < DateTime.Now.AddHours(24)); 
+0

感謝您的回答,但是如果問題中提到d.expires是DateTimeOffset,則不起作用。 – Chris 2010-10-17 16:05:38

+0

好的,再試一次,我已經調整了查詢​​來抵消類型。對不起,我錯過了 – danijels 2010-10-17 22:24:09

0
var list1 = 
    collection.Where 
     (c => c.expires.DateTime > DateTime.Now && 
       c.expires.DateTime < DateTime.Today.AddDays(1)); 

var list2 = 
    collection.Where 
     (c => c.expires.DateTime >= DateTime.Now && 
       c.expires.DateTime <= DateTime.Now.AddHours(24)); 
+0

感謝您的答案,但這不起作用時,如問題 – Chris 2010-10-17 16:06:06

-1

這是一個很好的做法,「緩存」的計算性能值,否則它會在每個循環來計算(如在哪裏做了循環內部):

DateTime tomorrow = DateTime.Today.AddDays(1); 
DateTime now = DateTime.Now; 
DateTime next24hrs = now.AddHours(24); 
IEnumerable<Sample> next24HoursSamples = collection.Where(sample=>sample.expires>now && sample.expires<next24hrs).ToList(); 
IEnumerable<Sample> sameDaySamples = next24HoursSamples.Where(sample=>sample.expires>=now && sample.expires<tomorrow).ToList(); 

請注意,同一天的列表是從已經過濾的列表中檢索的(同一天是未來24小時的一個子集),所以過濾的項目較少。

編輯:我更新了代碼以使用立即查詢執行模型,因爲@danijels警告延遲執行。

+0

中提到的c.expires是DateTimeOffset我不認爲這是非常明智的。由於Linq推遲執行,計算DateTime值並將它們傳遞給Linq意味着理論上,執行實際執行時,這些值可能已經改變。考慮到這個代碼在午夜前運行幾秒鐘就足夠了,並且在兩者之間進行一些操作以允許新的一天開始,並且一切都是錯誤的。更不用說這是否意味着在編譯的linq查詢中。 – danijels 2010-10-13 13:08:20

+0

這在理論上可能是正確的,但實際上延期執行也可能在午夜時間運行並且全部搞砸了。這只是一個好習慣,這不是一個規則。 – jaraics 2010-10-13 13:35:24