如何选择某一天的所有日期?

时间:2014-06-06 08:40:47

标签: sql asp.net-mvc linq

考虑到我想要获得同一周所有其他日期的日期,本周的开始和结束时间在周六和周五。

模型

public TimeModel
{
   public int ID
   public DateTime Day
}

我目前正在做什么

public Contrller{
private db = new ModelContext();

public AddDates(DateTime Date)
{
    List<Model> list = new List<Model>();      
    int n = 0;

   while(Date.DayofWeek != DayofWeek.Sauturday)
   Date = Date.AddDats(-1)  // keep subracting the date until I reach Saturday

   while(Date.DayofWeek != DayofWeek.Friday
  {
     list.Add(Find(Date)); 
    //Simply put for each date not Friday
    // I find the corresponding model (the one with the same date) 
    //and add it to the list 

     Date = Date.AddDays(1)
  }

   list.Add(Find(Date)); // To add the Friday date to list 


  }

注意:不完全是我的代码,只是简化我的问题。

总结我的解决方案:
a)减去给定日期直到星期六 b)找到与日期对应的模型 c)重复,直到我到达星期五为止 d)再次添加到列表中以包括星期五

是否可以创建一个linq / sql语句来简单地选择所需的模型(关于日期)?

1 个答案:

答案 0 :(得分:0)

您可以找到获得当周的示例实现。

        List<TimeModel> list = new List<TimeModel>();
        int n = 0;
        for (int i = 0; i < 200; i++)
            list.Add(new TimeModel{ID = i, Day = DateTime.Now.AddDays(-i)});


        var currentDay = new TimeModel() {ID = 0, Day = DateTime.Now};
        var previousSaturday = currentDay.Day.AddDays(-(int)currentDay.Day.DayOfWeek - 1);
        var nextFriday = previousSaturday.AddDays(6);

        var currentWeek = list.Where(p => p.Day.DayOfYear >= previousSaturday.DayOfYear && p.Day.DayOfYear <= nextFriday.DayOfYear).OrderBy(p => p.Day.DayOfYear).ToList();