Simplify if else condition using timespan in C#

寵の児 提交于 2019-12-04 06:54:10

Does this work for you?

var sqls = new []
{
    "select x from y",
    "select w from q",
    // etc - 24 options
};

var sql = sqls[DateTime.Now.Hour];

Or even:

var sqls = new Action[]
{
    () => { /* sql for midnight */ },
    () => { /* sql for 1 am */ },
    // etc
    () => { /* sql for 11 pm */ },
};

var sql = sqls[DateTime.Now.Hour];

sql.Invoke();

If you want DayOfWeek and Hour then you could use this:

var sqls = new string[][]
{
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
    new [] { "select x from y", "select w from q", },
};

var sql = sqls[(int)DateTime.Now.DayOfWeek][DateTime.Now.Hour];

Based on the comments and other answers, here's a more succinct way of doing it:

string day = DateTime.Now.DayOfWeek.ToString().Substring(0, 3);

string[] shifts = new []
{
    "('22:00-7:00')",
    "('22:00-7:00', '6:00-15:00')",
    // 24
};

string shift = shifts[DateTime.Now.Hour];

string sql = $"SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND shift IN {shifts} AND {day} = 'W'";

It sounds like you can vastly simplify your code by generating your SQL dynamically. I am guessing a bit as I don't know your data model fully, but something along the following:

var dayColumns = new [] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
var currentDayColumn = dayColumns[(int) DateTime.Now.DayOfWeek];

string shifts;

switch (DateTime.Now.Hour) {
  case 0:
    shifts = "('22:00-7:00')"
    break;
  case 6:
    shifts = "('22:00-7:00', '6:00-15:00')"
    break;
  //TODO - more cases
}

string sql = "SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND shift IN " + shifts + " AND " + currentDayColumn + " = 'W'";

If you can change the shift to two columns with the start and end hours, you can optimise it further like this:

var hour = DateTime.Now.Hour

string sql = "SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune' AND " + hour + " >= shift_start_hour AND " + hour + " < shift_end_hour AND " + currentDayColumn + " = 'W'";

Assuming your SQL also depends on WeekDay + Hour (otherwise it wouldn't make much sense?) you can do something like this:

protected void sample()
{
    var now = DateTime.Now;
    var sql = GetSql(now.DayOfWeek, now.Hour);
    // execute sql
}

protected string GetSql(DayOfWeek dayofweek, int hour)
{
    // generate sql, using "(int)dayofweek" if needed
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!