【问题标题】:Grouping a linq query with an external list with no gaps使用没有间隙的外部列表对 linq 查询进行分组
【发布时间】:2015-10-08 01:54:56
【问题描述】:

我需要从数据库中获取折线图的数据,其中流从当前日期 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 中的答案都很好,我都知道)

【问题讨论】:

    标签: .net linq linq-to-entities


    【解决方案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()
    

    您需要让异步工作正常工作,但查找可以很好地确保您包括所有天,包括那些没有数据的天。

    【讨论】:

      【解决方案2】:

      我会建议一种混合方法,您可以创建一个静态周期表(存储所有可能的范围),然后加入它们:

      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()})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-01
        • 2013-09-05
        • 1970-01-01
        • 2021-02-17
        • 2021-08-18
        相关资源
        最近更新 更多