2010-08-20 86 views
1

我用這個LINQ查詢在一個應用程序我寫:簡化LINQ查詢?

internal int GetNoteCount(DateTime startDate, DateTime endDate) 
{ 
    var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate); 
    var b = a.Where(n => n.LastRevised <= endDate); 
    return b.Count(); 
} 

顯然,查詢獲取落在兩個日期之間的注意事項。我想通過將前兩行合併爲一個來簡化查詢。我知道我可以使用流利的語法將Count()方法調用添加到查詢的末尾。

以下是我的問題:如何合併兩個查詢?顯然,& &運算符不能使用兩個lambda表達式。謝謝你的幫助。

回答

3

你可以這樣做:

internal int GetNoteCount(DateTime startDate, DateTime endDate) 
{ 
    return DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate).Count(); 
} 

只需使用你的條件,而不是整個拉姆達:)的&&

+0

不要忘記他正在返回.Count()。 – 2010-08-20 20:31:48

+0

@Jacob - woops,謝謝並加入:) – 2010-08-20 20:35:02

+0

謝謝!接受和+1 – 2010-08-20 20:46:23

1

首先,這有什麼不對的& &運營商,它應該只是罰款。

var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate); 
return a.Count(); 

其次,LINQ,它延遲執行查詢,直到.Count之間的(),所以就是你們的榜樣,這一次的功能沒有差異。