2015-10-08 28 views
1

我需要從數據庫中獲取線性圖的數據,其中數據流從當前日期n天/周/月/年按這些時間跨度分組。使用外部列表分組linq查詢沒有間隙

DB中的記錄具有與它們關聯的DateTime。

給定日期範圍列表(開始一天到一天結束或一週開始到一週結束)如何使用linq獲得連續流?

在正好沒有該日期範圍內的記錄的情況下,流中沒有空白是很重要的。它應該只返回一個零。

這是我試過的,但它不返回任何值。

Dim ranges = Enumerable.Range(0, itemCount).Select(Function(x) DateTime.Now.AddDays(-x).Date).ToList() 

    Dim stream = Await DB.LogEntries. 
     OfType(Of LogEntryContentView). 
     GroupBy(Function(x) DbFunctions.TruncateTime(x.DateStamp)). 
     Where(Function(x) ranges.Any(Function(y) y < x.Key AndAlso DbFunctions.AddDays(y, 1) > x.Key)). 
     OrderBy(Function(x) x.Key). 
     Select(Function(x) x.Count()). 
     ToListAsync() 

(用C#或VB.NET的答案都很好,我知道這兩個)

回答

1

最簡單的方法是使用.ToLookup(...)

你的查詢如下(東西)是這樣的:

Dim ranges = Enumerable.Range(0, itemCount).Select(Function(x) DateTime.Now.AddDays(-x).Date).ToList() 

Dim stream = DB.LogEntries. 
    OfType(Of LogEntryContentView). 
    GroupBy(Function(x) DbFunctions.TruncateTime(x.DateStamp)). 
    Where(Function(x) ranges.Any(Function(y) y < x.Key AndAlso DbFunctions.AddDays(y, 1) > x.Key)). 
    ToLookup(Function(x) x.Key) 

Dim results = ranges.Select(Function (d) stream(d).Count()).ToList() 

你需要得到異步東西工作,但查找不好聽確保你包括所有天,包括那些沒有的伎倆數據。

0

我建議在其中創建時期的靜態表(存儲所有可能的範圍內)的混合方法和然後加入它們:

db.LogEntries.Join(db.Periods, a=> true, b => true, (a,b) = > new {LE=a, P=b}) 
.Where (p=> p.LE.DateStamp >= p.P.PeriodStartDate && p.LE.DateStamp <= p.P.PeriodEndDate) 
.OrderBy(p=> p.P.PeriodStartDate) 
.GroupBy(p=> new{Start=p.P.PeriodStartDate, End=p.P.PeriodEndDate}) 
.Select(p=> new{Start=p.Key.Start, End=p.P.End, Count=p.Count()})