如何在EF中将数据分组两次?

时间:2011-03-02 05:20:40

标签: sql-server entity-framework entity-framework-4

这是我当前的LINQ查询:

            var list_1 = from z in _uow.Events.FindAll()
                     group z by new
                                    {
                                        z.GroupOfEvents.Customer,
                                        z.GroupOfEvents.GroupOfGroupOfEvents.Data.Year,
                                        z.GroupOfEvents.GroupOfGroupOfEvents.Data.Month,
                                        z.GroupOfEvents.GroupOfGroupOfEvents.Data.Day
                                    }
                         into zz
                         select new
                                    {
                                        zz.Key.Customer.Id,
                                        zz.Key.Year,
                                        zz.Key.Month,
                                        zz.Key.Day,
                                        Amount = zz.Sum(a => a.Amount)
                                    };

我希望按客户ID分组数据,然后按天(年 - 月 - 日)分组。所以我想每个客户每天访问特定的“金额”。知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

到目前为止,我带来了这个,但我不确定这是不是最好的方式?

            var list_a =
            from klient in _uow.Klient.FindAll()
            select
                new
                    {
                        Klient = klient,
                        Days =
                from grupaZdarzen in klient.GrupaZdarzen
                group grupaZdarzen by new
                                          {
                                              grupaZdarzen.ZestawGrupZdarzen.Data.Year,
                                              grupaZdarzen.ZestawGrupZdarzen.Data.Month,
                                              grupaZdarzen.ZestawGrupZdarzen.Data.Day
                                          }
                into grupyZdarzenByDay
                select new
                           {
                               Data = grupyZdarzenByDay.Key,
                               Total =
                    (from grupaZdarzenByDay in grupyZdarzenByDay
                     from zdarzeniaByGrupa in grupaZdarzenByDay.Zdarzenie
                     select zdarzeniaByGrupa.Ilosc).Sum()
                           }
                    };

        var list_b = list_a.ToDictionary(a => a.Klient.Id,
                                         a =>
                                         a.Days.ToDictionary(
                                             b => b.Data.Day + "/" + b.Data.Month + "/" + b.Data.Year, b => b.Total));