我需要从数据库中获取折线图的数据,其中流从当前日期返回n天/周/月/年按时间盘分组。
数据库中的记录具有与之关联的日期时间。
给出日期范围列表(一天开始到一天结束或一周开始到一周结束)我如何使用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中的答案都很好,我知道两者都是)
答案 0 :(得分: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()
你需要让异步的东西工作,但查找很好地确保你包括所有日子,包括没有数据的那些日子。
答案 1 :(得分:0)
我建议使用混合方法,在其中创建一个Periods的静态表(存储所有可能的范围),然后加入它们:
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()})