如何按日期范围对列表进行分组

时间:2011-05-26 14:19:43

标签: c# .net c#-2.0

我想按照DateRange每周或每季度将我的列表中的持续时间加起来。

我不确定这是最好的方法。

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

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

我正在使用LingBridge库,它允许在.net-2.0

中使用lambda表达式

4 个答案:

答案 0 :(得分:1)

您需要使用forforeach或类似内容对您的收藏进行迭代。

例如Q1:

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

答案 1 :(得分:1)

这是一些2.0兼容的代码,用于在日期上实现分组。您可以对其进行调整,以便对类的DateTime 属性进行分组。

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);
     }
}

答案 2 :(得分:0)

这将按年份分组:

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

因此,现在您只需要弄清楚日期的WeekOfYear或QuarterOfYear属性,并将其用作分组子句。

对于QuarterOfYear,这看起来像这样:

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

但就本周而言,这变得更加复杂。据我所知,有不同的方法可以开始计算一年内的数周。检查NodaTime或其他一些日期库,为你做这件事......

答案 3 :(得分:0)

与所有日期一起返回。

event.Sort((x, y) => DateTime.Compare(x.date, y.date));
相关问题