c# - 检查时间范围是否在 C# 中相交

标签 c# .net winforms algorithm visual-studio-2012

<分区>

我目前正在用 C# 开发一个简单的注册系统,我在考虑是否有一种直接的方法来检查我的输入 session 的特定时间范围(从 - 到)是否与数据库中的时间范围相交。

场景如下:

我的数据库中有一个名为 tblSessionList 的表,它存储每个主题的不同 session ,我想在每次用户添加新 session 时检查是否有特定的 Room已经占据了那个特定的时间范围。从技术上讲,我想检查选择的时间范围是否与 tblSessionList 中的 session 不冲突。

Add Session Form

tblSessionList

 | Subject Code |   Venue    |   Room   |        Date             |  From   |   To    |
 |              |            |          |                         |         |         |
 |   CRGOV401   |  GT Tower  | Room 3D  | Thursday, June 19, 2014 | 8:00 AM |10:00 AM |
 |   CRGOV401   |  GT Tower  | Room 59  | Sunday, June 29, 2014   | 1:00 PM |3:00  PM |
 |   GNBNK201   | Main Plaza | HR Hall  | Monday, June 30, 2014   | 9:00 AM |11:00 AM |
 |   GNBNK201   | Main Plaza | HR Hall  | Monday, June 30, 2014   | 1:00 PM |3:00     |

我已尝试执行以下操作:

 private void btnAddSession_Click(object sender, EventArgs e)
    {
        bool proceedCopy = true;

        DataTable timeHolder = new DataTable();
        SqlDataAdapter selectTime = new SqlDataAdapter("select [From],[To] from tblSessionList where [Venue] = @venue and [Room] = @room", Connection.conn);
        selectTime.SelectCommand.Parameters.AddWithValue("@venue", venue.Text);
        selectTime.SelectCommand.Parameters.AddWithValue("@room", room.Text);

        selectTime.Fill(timeHolder);


        for(int i = 0; i < timeHolder.Rows.Count; i++)
       {

        if(timeHolder[i][0].toString() == From.Text) //checks if the 'From' of the query is the same with the 'From' of the new entry
              {
                MessageBox.Show("The room is already occupied on that time range");
                proceedCopy = false;
                break;
              }

        else if(timeHolder[i][1].toString() == To.Text) //checks if the 'To' of the query is the same with the 'To' of the new entry.
              {
                 MessageBox.Show("The room is already occupied on that time range");
                 proceedCopy = false;
                 break;
              }
        }
       if(proceedCopy == true)
           //insert code to insert new session to database here
    }

这是一个硬编码检查,它只检查时间范围的终点,而不是时间范围本身。我在想 C# 中是否有一个函数可以像 Time only 而不是 DateTime 那样使用。

注意:我数据库中的每一列都是一个 varchar。很抱歉,这是我的第一个系统,有脏代码。

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用 interval tree搜索数据库。间隔树存储一个范围 (a,b) 并使用两个间隔之间的比较从中构建一个 BST,并决定它是向左还是向右。区间树的搜索可以在 O(logn) 中完成。

关于c# - 检查时间范围是否在 C# 中相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276364/

相关文章:

c# - Web 服务方法 - 无法序列化,因为它没有无参数构造函数

C# Web 请求-HTTP : 403 Forbidden ('_xsrf' argument missing from POST)

c# - 从 wpf 中检索 gridview 选定行中的值

c# - 调整 ListView 列以适应 WinForms

c# - 拆分器控件(winforms)

c# - 排序后变量为空

c# - 将 Nullable<T> 与值类型一起使用的错误做法?

c# - 隐藏 .NET MessageBox 的任务栏图标

.net - 使用 ILMerge 时无法加载 mscorsn.dll

c# - 为什么将 Winforms DateTimePicker 设置为 DateTime.MinValue 会失败?