循环时间周期得到周

本文关键字:周期 时间 循环 | 更新日期: 2023-09-27 17:49:42

如果我有一个约会列表,想在一周内完成,而不是在一个循环中完成,

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的时间段,并且开始日期01-02将作为开始周。

因此,从02到08的项目是一个星期09-16另一个,以此类推,直到结束,在它的一周没有7天。我怎么能迭代列表和传递只是特定的周到另一个方法没有预先计算"周制动日期"只是添加7天,直到结束?

循环时间周期得到周

下面的代码返回第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; }
}

您可以通过在约会上使用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());
}

您需要实现GetWeekOfYear (http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx) -但是对于任何给定的约会列表和给定的周数,这将返回该周的所有约会。