2

I am looking for some help on adapting the following LINQ query to return all dates within the next 6 months, even those where no records fall within the given month.

var maxDate = DateTime.Now.AddMonths(6);

var orders = (from ord in db.Items

where (ord.Expiry >= DateTime.Now && ord.Expiry <= maxDate)

group ord by new
    {
        ord.Expiry.Value.Year,
        ord.Expiry.Value.Month
    }
into g
select new ExpiriesOwnedModel
    {
        Month = g.Select(n => n.Expiry.Value.Month).First(),
        Quantity = g.Count()
    }).ToList();

I'd really appreciate any assistance or pointers on how best to implement this.

4

3 に答える 3

3

データベースとどの程度うまくやり取りできるかはわかりませんが、結合と同じようにこれを行います。

var firstDaysOfMonths = Enumerable.Range(0, 7).Select(i =>
    new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(i));
var orders = firstDaysOfMonths.GroupJoin(
    db.Items,
    fd => fd,
    ord => new DateTime(ord.Expiry.Value.Year, ord.Expiry.Value.Month, 1),
    (fd, ords) => new { Month = fd.Month, Quantity = ords.Count() });

以前はそうではなかった余分な月が発生する可能性があることに注意してください(月の最初の日?)

于 2012-11-07T16:33:25.663 に答える
2

グループ結合のクエリ構文を好む場合は、ローリングの回答から盗みました(私はそうします):

var orders =
    from month in Enumerable.Range(0, 7)
        .Select(i => new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(i))
    join ord in db.Items
        on month equals new DateTime(ord.Expiry.Value.Year, ord.Expiry.Value.Month, 1)
        into ords
    select new { month.Month, Quantity = ords.Count() };
于 2012-11-07T16:48:35.070 に答える
0

データベースでうまくいかない場合の代替手段:

var rawGroups = db.Items.Where(item.Expiry >= DateTime.Now && ord.Expiry <= maxDate)
                        .GroupBy(item => new
                           {
                            item.Expiry.Value.Year,
                            item.Expiry.Value.Month
                           }, g => new ExpiriesOwnedModel()
                          {
                            Month = g.Key.Month,
                            Quantity = g.Count()
                          }).ToDictionary(model => model.Month);

var result = Enumerable.Range(DateTime.Now.Month,6)
                       .Select(i => i > 12 ? i - 12 , i)
                       .Select(i => rawGroups.Keys.Contains(i) ?
                                    rawGroups[i] :
                                    new ExpiriesOwnedModel() 
                                    { Month = i , Quantity = 0 });
于 2012-11-07T17:15:37.580 に答える