Brad
Brad

Reputation: 21160

how do you group a list by date range

I would like to sum the durations in my List by DateRange by either weekly or quarterly.

I am not sure to the best approach for this.

 List<Event> events = new List<Event>();

 class Event
 {
     public string EventName {get;set;}
     public DateTime date {get;set;}
     public double duration {get; set;}
 }

I am using the LingBridge library which will allow for lambda expressions in .net-2.0

Upvotes: 1

Views: 1319

Answers (4)

Anthony Pegram
Anthony Pegram

Reputation: 126884

Here is some 2.0 compatible code to achieve grouping on a date. You can adapt it for grouping on a DateTime property of a class.

List<DateTime> dates = ...

Dictionary<int, IList<DateTime>> groupedDates 
    = new Dictionary<int, IList<DateTime>>();

foreach (DateTime date in dates)
{
     int quarter = (date.Month / 3) + 1;
     if (groupedDates.ContainsKey(quarter)) 
     {
         groupedDates[quarter].Add(date);
     }
     else  
     {
         List<DateTime> dateGroup = new List<DateTime>();
         dateGroup.Add(date);
         groupedDates.Add(quarter, dateGroup);
     }
}

Upvotes: 1

Joshua
Joshua

Reputation: 552

In place return with dates all together.

event.Sort((x, y) => DateTime.Compare(x.date, y.date));

Upvotes: 0

Lazarus
Lazarus

Reputation: 43084

You are going to need to iterate over your collection using for or foreach or similar.

For Q1 for example:

List<Event> Q1Events = new List<Event>();
foreach (Event e in events)
{
    if (e.date.Month >= 1 && e.date.Month <= 3) 
        Q1Events.Add(e);
}

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70324

This would group it by day of year:

events.GroupBy(e => string.Format("{0}.{1}+", e.date.DayOfYear, e.date.Year);

So, now you just have to figure out the WeekOfYear or QuarterOfYear property of a date and use that as your grouping clause.

For QuarterOfYear, this could look something like this:

events.GroupBy(e => string.Format("{0}.{1}+", (e.date.Month % 4) + 1, e.date.Year);

But for the week, well, that gets more complicated. As far as I recall, there are different ways to start counting weeks in a year. Check NodaTime or some other date library to do that for you...

Upvotes: 0

Related Questions