显示按星期几分组的事件列表

时间:2015-04-17 16:58:22

标签: c# sql asp.net webforms

我试图根据sql server数据库中的数据条目显示每天的事件列表。我希望它在页面上显示如下:

Monday - Title1 Title2
Tuesday - Title3
Wednesday - Title4 Title5

现在我的数据看起来像这样

Title  | StartDate
Title1 | 2015-04-20 16:46:00.00
Title2 | 2015-04-20 12:46:00.00
Title3 | 2015-04-21 16:46:00.00
Title4 | 2015-04-22 1:46:00.00
Title5 | 2015-04-22 13:12:00.00

我只需要接下来的7天。我对此非常陌生,这就是我试图做的事情,但这根本不符合我的想法。

StringBuilder el = new StringBuilder();
using (SqlConnection conn = new SqlConnection(""))
{
            SqlCommand cmd = new SqlCommand(@"select * from Event where
                                            convert(datetime, StartDate , 101) >= DATEADD(d,DATEDIFF(d,0,getdate()),0) 
                                            order by StartDate", conn);
            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                DateTime start = DateTime.Now;
                DateTime end = DateTime.Now.AddDays(7);
                int days = (end - start).Days;
                Enumerable
                    .Range(0, days)
                    .Select(x => start.AddDays(x))
                    .ToList()
                    .ForEach(d =>
                    {
                        DayOfWeek dayOfWeek = d.DayOfWeek;
                        el.Append("<strong>" + Convert.ToDateTime(rdr["StartDate"].ToString()).DayOfWeek + "</strong><br />");
                        el.Append(rdr["Title"].ToString() + "<br />");
                    });
            }
            rdr.Close();
}
Label1.Text = el.ToString();

1 个答案:

答案 0 :(得分:1)

在代码中处理它的一种方法是跟踪处理的最后一天并在每次更改时打印该日。请参阅下面的示例。

StringBuilder el = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connString)) {
  SqlCommand cmd = new SqlCommand(@"
              select * from Event 
              WHERE DATEDIFF(d, getdate(), StartDate) BETWEEN 0 and 6
              order by StartDate", conn);
  conn.Open();
  SqlDataReader rdr = cmd.ExecuteReader();

  if (rdr.HasRows) {
    rdr.Read();
    System.DayOfWeek lastDayProcessed = (DateTime)rdr["StartDate"]).DayOfWeek;
    el.AppendLine("<strong>" + lastDayProcessed + "</strong> -");
    el.Append(" " + rdr["Title"].ToString());

    while (rdr.Read()) {
      if (((DateTime)rdr["StartDate"]).DayOfWeek != lastDayProcessed) {
        // print the Day heading whenever the day changes
        el.AppendLine("<br />");
        lastDayProcessed = ((DateTime)rdr["StartDate"]).DayOfWeek;
        el.AppendLine("<strong>" + lastDayProcessed + "</strong> -");
      }
      el.Append(" " + rdr["Title"].ToString());
    }
  }
  rdr.Close();
}

我调整WHERE子句拉七天;今天和接下来的六天。