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 开发者_如何学Goallow for lambda expressions in .net-2.0
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);
}
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);
}
}
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...
In place return with dates all together.
event.Sort((x, y) => DateTime.Compare(x.date, y.date));
精彩评论