2012-12-27 49 views
1

如果我有一個約會列表,並希望在一個周而不是一個循環中獲得這些,例如。循環遍歷時間週期得到幾周

public class appointments 
{ 
    public string Appointment { get; set; } 
    public DateTime Start { get; set; } 
    public string Location { get; set; } 
} 

List<appointments> appointment = new List<appointments>(); 

appointment.Add(new appointments() { Appointment = "meeting", Start = new DateTime(2013, 01,02), Location = "office"}); 
appointment.Add(new appointments() { Appointment = "lunch", Start = new DateTime(2013, 01, 07), Location = "cafe" }); 
appointment.Add(new appointments() { Appointment = "meeting", Start = new DateTime(2013, 01, 08), Location = "cityhall" }); 
appointment.Add(new appointments() { Appointment = "dentist", Start = new DateTime(2013, 01, 14), Location = "dentist" }); 

現在我想從說2013-01-022013-01-25一個TIMEPERIOD,並開始日期01-02將要開始的一週。

因此,02到08之間的項目是一個星期09-16另一個等等,直到最後一個星期內有7天。我怎麼能迭代列表,並將特定的星期傳遞給另一個方法,而不需要預先計算「星期制動日期」,直到結束時加上7天?

+0

在某個特定的日子裏,像星期一或星期天一樣開始嗎?或者,你只是想以7天的塊來迭代嗎? – Jodrell

回答

1

下面的代碼返回1周「牙醫」和「會議,午餐會」一週0

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<appointments> appointment = new List<appointments>(); 

     appointment.Add(new appointments() { Appointment = "meeting", Start = new DateTime(2013, 01, 02), Location = "office" }); 
     appointment.Add(new appointments() { Appointment = "lunch", Start = new DateTime(2013, 01, 07), Location = "cafe" }); 
     appointment.Add(new appointments() { Appointment = "meeting", Start = new DateTime(2013, 01, 08), Location = "cityhall" }); 
     appointment.Add(new appointments() { Appointment = "dentist", Start = new DateTime(2013, 01, 14), Location = "dentist" }); 

     foreach (var appt in GetAppointmentsByWeek(appointment, 1)) 
      Console.WriteLine(appt.Appointment); 

     Console.ReadLine(); 
    } 

    private static IEnumerable<appointments> GetAppointmentsByWeek(List<appointments> appts, int weeknum) 
    { 
     if (weeknum < 0) 
      return new appointments[] { }; 

     var ordered = appts.OrderBy(a => a.Start.Ticks);   
     var start = ordered.First().Start.AddDays(weeknum * 7); 
     var end = start.AddDays(7); 
     return ordered.Where(o => o.Start.Ticks >= start.Ticks && o.Start.Ticks <= end.Ticks); 
    } 
} 

public class appointments 
{ 
    public string Appointment { get; set; } 
    public DateTime Start { get; set; } 
    public string Location { get; set; } 
} 
0

您可以通過上述任命將它們分組使用GroupBy由特定周做。這段代碼沒有經過測試和免費,但你應該明白。

private static IEnumerable<appointments> GetAppointmentsByWeek(List<appointments> appts, int weeknum) 
{ 
    var WeekGroup = appts.GroupBy(ap => GetWeekOfYear(ap.Start)).Where(gp => gp.Key == weeknum).FirstOrDefault(); 

    if (WeekGroup == null) {return new List<appointments>();} //No appointments for this week 

    return WeekGroup.Select(gp => gp.ToList()); 
} 

您需要實現GetWeekOfYearhttp://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx) - 但這約會的任何給定的名單和給定的週數將返回所有約會的那個星期。