2015-10-08 26 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()})