0

I'm still learning LINQ and have a task where I need to group Booking objects by four properties and then by weekly intervals depending on the input timerange.

public class Booking
{
    public string Group { get; set; }
    public BookingType Type { get; set; }
    public BookingStatus Status { get; set; }
    public decimal Price { get; set; }
    public bool Notification { get; set; }
    public DateTime Date { get; set; }
}

Let's say we have the following Bookings:

        IList<Booking> Bookings = new List<Booking>
        {
            new Booking{Group = "Group1", Type = BookingType.Online, Status = BookingStatus.New, Price = 150, Date = new DateTime(2012,06,01)},
            new Booking{Group = "Group1", Type = BookingType.Online, Status = BookingStatus.New, Price = 100, Date = new DateTime(2012,06,02)},
            new Booking{Group = "Group1", Type = BookingType.Online, Status = BookingStatus.New, Price = 200, Date = new DateTime(2012,06,03)},

            new Booking{Group = "Group2", Type = BookingType.Phone, Status = BookingStatus.Accepted, Price = 80, Date = new DateTime(2012,06,10)},
            new Booking{Group = "Group2", Type = BookingType.Phone, Status = BookingStatus.Accepted, Price = 110, Date = new DateTime(2012,06,12)},

            new Booking{Group = "Group3", Type = BookingType.Store, Status = BookingStatus.Accepted, Price = 225, Date = new DateTime(2012,06,20)},

            new Booking{Group = "Group3", Type = BookingType.Store, Status = BookingStatus.Invoiced, Price = 300, Date = new DateTime(2012,06,21)},
            new Booking{Group = "Group3", Type = BookingType.Store, Status = BookingStatus.Invoiced, Price = 140, Date = new DateTime(2012,06,22)},
        };

That would result in the following lines on the final printout:

                                        Week 22     Week 23     Week 24     Week 25     Week 26
                                        May28-Jun3  Jun4-10     Jun11-17    Jun18-24    Jun25-Jul1
            Group   Type    Status      Cnt. Price  Cnt. Price  Cnt. Price  Cnt. Price  Cnt. Price
            ----------------------------------------------------------------------------------------------
            Group1  Online  New         3   450     0   0       0   0       0   0       0   0
            Group2  Phone   Accepted    0   0       1   80      1   110     0   0       0   0
            Group3  Store   Accepted    0   0       0   0       0   0       1   225     0   0       
            Group3  Store   Invoiced    0   0       0   0       0   0       2   440     0   0           

I have created 2 additional classes to represent a line with the possibility to include any number of weeks:

 public class GroupedLine
{
    public string Group { get; set; }
    public BookingType Type { get; set; }
    public BookingStatus Status { get; set; }
    public List<WeeklyStat> WeeklyStats { get; set; } 
}

public class WeeklyStat
{
    public DateTime WeekStart { get; set; }
    public decimal Sum { get; set; }
    public int Count { get; set; }
}

If I have the following time period:

        var DateFrom = new DateTime(2012, 05, 28);
        var DateTo = new DateTime(2012, 7, 01);

Firstly, I need to identify what weeks are necessary in the statistics: in this case week 22-26.

For that I have the following code:

        var DateFrom = new DateTime(2012, 05, 28);
        var DateTo = new DateTime(2012, 7, 01);

        var firstWeek = GetFirstDateOfWeek(DateFrom, DayOfWeek.Monday);
        IList<DateTime> weeks = new List<DateTime> { firstWeek };

        while(weeks.OrderByDescending(w => w).FirstOrDefault().AddDays(7) <= DateTo)
        {
            weeks.Add(weeks.OrderByDescending(w => w).FirstOrDefault().AddDays(7));
        }

And now, I'd need some LINQ magic to do the grouping both by the 4 properties and the aggregation (count of bookings and sum of prices) for the weeks.

I can attach code sample of the LINQ I got so far tomorrow, as I don't have access to it now. Sorry for the long post, hope it's clear what I mean.

Edit: 2012-11-07 I have to modify the question a bit, so that the grouped weeks only include those weeks, that actually have data. Updated example output:

                                        May28-Jun3  Jun4-10     Jun18-24    
            Group   Type    Status      Cnt. Price  Cnt. Price  Cnt. Price  
            ---------------------------------------------------------------
            Group1  Online  New         3   450     0   0       0   0       
            Group2  Phone   Accepted    0   0       1   80      0   0       
            Group3  Store   Accepted    0   0       0   0       1   225             
            Group3  Store   Invoiced    0   0       0   0       2   440         

In this case there were no Bookings in period Jun 11-17 and Jun25-Jul1 so they are omitted from the results.

3 Answers 3

1

This query will get all data

var query = from b in Bookings
            where b.Date >= dateFrom && b.Date <= dateTo
            group b by new { b.Group, b.Type, b.Status } into g
            select new GroupedLine()
            {
                Group = g.Key.Group,
                Type = g.Key.Type,
                Status = g.Key.Status,
                WeeklyStats = (from b in g
                                let startOfWeek = GetFirstDateOfWeek(b.Date)
                                group b by startOfWeek into weekGroup
                                orderby weekGroup.Key
                                select new WeeklyStat() 
                                {
                                    WeekStart = weekGroup.Key,
                                    Count = weekGroup.Count(),
                                    Sum = weekGroup.Sum(x => x.Price)

                                }).ToList()
            };

I leave UI output to you :)

This will also return WeekStats for all weeks (with 0 values, if we do not have booking groups on some week):

// sequence contains start dates of all weeks
var weeks = Bookings.Select(b => GetFirstDateOfWeek(b.Date))
                    .Distinct().OrderBy(date => date);

var query = from b in Bookings
            group b by new { b.Group, b.Type, b.Status } into bookingGroup
            select new GroupedLine()
            {
               Group = bookingGroup.Key.Group,
               Type = bookingGroup.Key.Type,
               Status = bookingGroup.Key.Status,
               WeeklyStats = (from w in weeks
                              join bg in bookingGroup 
                              on w equals GetFirstDateOfWeek(bg.Date) into weekGroup
                              orderby w
                              select new WeeklyStat() 
                              {
                                  WeekStart = w,
                                  Count = weekGroup.Count(),
                                  Sum = weekGroup.Sum(b => b.Price)    
                              }).ToList()
            };

Keep in mind, that if you need date filter (from, to), then you need to apply it both to weeks query and bookings query.

10
  • Hey, this looks great! Just a small thing: might be easier for UI purposes if all GroupedLines would have WeeklyStats for all the weeks (even with 0 values).. How would I need to modify the query?
    – akrobet
    Oct 17, 2012 at 19:47
  • Hello again! One additional task I have and I seem to block when it comes to linq, is to create a summary line with the sum of sums and counts, this time grouped by the weeks they are in. So e.g. week 25 would result in Total: Count: 3 Sum: 665. It could take the result of previous query or just the bookings again...
    – akrobet
    Oct 19, 2012 at 11:18
  • @akrobet I think you can create new question for this :) Also specify there what have you tried to do Oct 19, 2012 at 11:27
  • Heh, after some coffee I figured out it's basically the same query as the WeeklyStats from your solution, without grouping them first...
    – akrobet
    Oct 19, 2012 at 13:42
  • @akrobet congratulations :) You did one more step in knowing Linq! Oct 19, 2012 at 13:45
0
var query = Bookings.GroupBy(book => new GroupedLine()
{
    Group = book.Group,
    Type = book.Type,
    Status = book.Status
})
.Select(group => new
{
    Line = group.Key,
    Dates = group.GroupBy(book => GetWeekOfYear(book.Date))
        .Select(innerGroup => new
        {
            Week = innerGroup.Key,
            Count = innerGroup.Count(),
            TotalPrice = innerGroup.Sum(book => book.Price)
        })
});

public static int GetWeekOfYear(DateTime date)
{
    return date.DayOfYear % 7;
}
1
  • Appreciate the answer, chose @lazyberezovsky's because it worked out of the box.
    – akrobet
    Oct 17, 2012 at 20:37
0

This variant generates "empty" spots for weeks with no data:

// I group by week number, it seemed clearer to me , but you can change it
var firstWeek = cal.GetWeekOfYear(DateFrom, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
var lastWeek  = cal.GetWeekOfYear(DateTo, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);

var q = from b in Bookings
        group b by new { b.Group, b.Type, b.Status }
        into g
        select new 
        {
            Group = g.Key,
            Weeks = 
                from x in g
                select new 
                { 
                    Week = cal.GetWeekOfYear(x.Date,
                                             dfi.CalendarWeekRule, 
                                             dfi.FirstDayOfWeek), 
                    Item = x 
                }   
        } into gw
        from w in Enumerable.Range(firstWeek, lastWeek-firstWeek+1) 
        select new 
        { 
            gw.Group,
            Week = w,
            Item = from we in gw.Weeks
                   where we.Week == w
                   group we by we.Item.Group into p 
                   select new 
                   {
                       p.Key,
                       Sum = p.Sum (x => x.Item.Price),
                       Count = p.Count()
                   }
        };
2
  • Thanks for the reply, chose @lazyberezovsky's because it was more clear to me.
    – akrobet
    Oct 17, 2012 at 20:36
  • No problem, actually I realized I didn't know about a small detail that in @lazyberezovsky's answer is clear, and it helps building a cleaner expression, I learned something new :)
    – Wasp
    Oct 17, 2012 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.