【问题标题】:Linq to Entity, selecting group without valueLinq to Entity,选择没有价值的组
【发布时间】:2012-07-25 15:47:05
【问题描述】:

我希望能够按月份对我的所有数据进行分组,即使某些月份不包含任何数据。此时,我可以分组,但返回的数据只包含带数据的月份。

我的代码如下所示:

var twelveMonthAgo = date.AddMonths(-12).Date;
var twelveMonthAgoFirstOfMonth = new DateTime(twelveMonthAgo.Year, twelveMonthAgo.Month, 1, 0, 0, 0, 0);

var data = (from i in Database.Users
            where i.RegisterDate >= twelveMonthAgoFirstOfMonth
            group i by new {y=i.RegisterDate.Year,m = i.RegisterDate.Month} into g
            select new UserStatistic{ Date = EntityFunctions.CreateDateTime(g.Key.y, g.Key.m, 1, 0, 0, 0)
                                       , UserCount = g.Count(o => o.Id)
                                     });

//The code below is what I would like to remove                                         
var toReturn = new List<UserStatistic>();
var allData = data.ToList();
DateTime datei = twelveMonthAgoFirstOfMonth;
while (datei.Year<= date.Year && datei.Month<=date.Month){
    var info = allData.SingleOrDefault(x => x.Date.HasValue && x.Date.Value.Year == datei.Year && x.Date.Value.Month == datei.Month);
    toReturn.Add(info ?? new UserStatistic { Date = datei, UserCount = 0, PaymentPaid = 0 });
    datei = datei.AddMonths(1);
}
return toReturn.AsQueryable();   

如你所见,cmets下的代码构建了一个最近12个月的集合,并检查是否有一些数据已经出库,如果有则填充集合,否则置0。

我怎样才能做到这一切,而不必做评论下方的代码?

【问题讨论】:

  • 是第一个月,data 中的第一个月还是一月(1) 还是第一年?同样,最后一个月应该是去年的 12 月 (12) 还是 data 的最后一个月?
  • 您需要对聚合值的日期执行左外连接。分组依据将始终忽略不分组的值。
  • @Jodrell 日期范围无关紧要,这可能会改变。我想要的是获得最近 x 个月的数据。
  • @casperOne 好的,任何示例,因为理想情况下我不想在此方法中使用 .ToList() 以便能够返回真正的 IQueryable。

标签: c# .net entity-framework ef-code-first


【解决方案1】:

下面是一些使用组连接到子查询的代码来获得你想要的结果:

DateTime date = DateTime.Today;
DateTime firstOfMonth = new DateTime(date.Year, date.Month, 1);
DateTime twelveMonthAgoFirstOfMonth = firstOfMonth.AddMonths(-12);

// Generate a collection of the months and years for the last 12 months
var monthYears = Enumerable.Range(-12, 12).Select(monthOffset => { DateTime monthDate = firstOfMonth.AddMonths(monthOffset); return new { y = monthDate.Year, m = monthDate.Month }; });

// Go through the list of months and years and join them to the users retrieved from the database in the subquery.
var data = from monthYear in monthYears
           join i in (from i in Database.Users
                      where i.RegisterDate >= twelveMonthAgoFirstOfMonth && i.RegisterDate < firstOfMonth
                      select i) on monthYear equals new { y = i.RegisterDate.Year, m = i.RegisterDate.Month } into gj
           select new UserStatistic() { Date = new DateTime(monthYear.y, monthYear.m, 1), UserCount = gj.Count() });

这也可以表示为带有左外连接的子查询中的组:

    DateTime date = DateTime.Today;
    DateTime firstOfMonth = new DateTime(date.Year, date.Month, 1);
    DateTime twelveMonthAgoFirstOfMonth = firstOfMonth.AddMonths(-12);
    var monthYears = Enumerable.Range(-12, 12).Select(monthOffset => { DateTime monthDate = firstOfMonth.AddMonths(monthOffset); return new { y = monthDate.Year, m = monthDate.Month }; });

    var data = (from monthYear in monthYears
                join i in (from i in Database.Users
                           where i.RegisterDate >= twelveMonthAgoFirstOfMonth && i.RegisterDate < firstOfMonth
                           group i by new {y = i.RegisterDate.Year, m = i.RegisterDate.Month} into g
                           select new { Key = g.Key, UserCount = g.Count() }) on monthYear equals i.Key into j
                 from k in j.DefaultIfEmpty()
                 select new UserStatistic() { Date = new DateTime(monthYear.y, monthYear.m, 1), UserCount = k != null ? k.UserCount : 0 });

由于我没有你的 EF 型号,你必须尝试一下,看看是否需要将 new DateTime 替换为 EntityFunctions.CreateDateTime。

【讨论】:

  • 你的第二个例子正是我的例子!它运作良好。非常感谢您的意见。
【解决方案2】:

我还没有编译和调试过这个,但它应该让我知道我认为你可以如何解决你的问题。我使用Enumerable.Range 为您需要的月份生成一组占位符。然后我不得不在将placeHolders 加入data 和合并或者只是连接省略之间做出选择。

我还稍微修改了问题中的代码以帮助我理解它。

IQueryable<UserStatistic> GetPastMonths(int months)
{    
    var limitDay = date.AddMonths(-months).Date;
    var limit = new DateTime(limitDay.Year, limitDay.Month, 1, 0, 0, 0, 0);

    var placeHolders = Enumerable.Range(0, months + 1)
        .Select(m =>
            new UserStatistic
                {
                    Date = limit.AddMonths(-m),
                    UserCount = 0
                });

    var data = Database.Users
        .Where(i => i.RegisterDate >= limit)
        .GroupBy(i => new {y=i.RegisterDate.Year, m = i.RegisterDate.Month})
        .Select(g => 
            new UserStatistic
                { 
                    Date = EntityFunctions.CreateDateTime(
                            g.Key.y,
                            g.Key.m, 
                            1, 
                            0, 
                            0, 
                            0),
                    UserCount = g.Count(o => o.Id)
                });

    return data.Concat(placeHolders
        .Where(p => !data.Any(d => d.Date == p.Date)))
        .AsQueryable();
}

连接遗漏的方法几乎可以保证以不合逻辑的顺序返回数据,但是,除非您使用 order by 子句,否则无论如何您都没有 garauntees。

【讨论】:

  • 这看起来很接近我现在正在试验的东西。让我完成我的示例,然后我会更仔细地查看您的示例。谢谢
猜你喜欢
  • 2012-12-26
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多