如果我有一个约会列表,并希望在几周内获得这些约会,例如。
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-02
到2013-01-25
的时间段,并且startdate 01-02将是开始周。
所以02到08之间的项目是一周09-16另一个,依此类推,直到结束,其中一周有7天。我怎么能迭代列表并将特定的周传递给另一个方法而不预先计算“周制动日期”只需要添加7天直到结束?
答案 0 :(得分: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; }
}
答案 1 :(得分: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());
}
您需要实施GetWeekOfYear
(http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx) - 但是对于任何给定的约会列表和给定的周数,这将返回该周的所有约会。