JSon.Mvc JSon.Mvc - 4 months ago 17
ASP.NET (C#) Question

select row with multiple period time field

i use asp.net mvc and c#
i have data table that have many column,one column has 'time' and sotred data like this format

14
16:30
17:05
...


in view i have filter for time and user can select multiple time from check box,
my filter check box is

4 - 8
8 - 11
11 - 14
14 - 17
17 - 21
21 - 24


now i want filter from datatable

var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("time") // between any passed time,like between 4-8 and 11-14 and 21-24
select r;
DataTable dtResult = result.CopyToDataTable();


my problem is,i dont know user how many pass time , if just passed one time it's easy but i dont know how many time passed

how i can edit code for accept any time and any count of time?

thank you for your help

Answer

You can do something like this:

string input = "4 - 17"; // The input from your check box

var sections = input.Split('-');
int beginHour = int.Parse(sections[0].Trim());
int endHour = int.Parse(sections[1].Trim());

var result = from r in myDataTable.AsEnumerable()
             let time = int.Parse(r.Field<string>("time").Split(':')[0])
             where time >= beginHour && time < endHour
             select r;

Make sure you handle cases where parsing to int might fail


Of a collection of input ranges you can do something like:

List<string> originalData = new List<string> { "4 - 8", "8 - 11", "11 - 14", "14 - 17"};

var ranges = originalData.Select(item =>
{
    var sections = item.Split('-');
    return new
    {
        RangeBegin = int.Parse(sections[0].Trim()),
        RangeEnd = int.Parse(sections[1].Trim())
    };
}).ToList();

var result = from r in myDataTable.AsEnumerable()
             let time = int.Parse(r.Field<string>("time").Split(':')[0])
             from range in ranges
             where time >= range.RangeBegin && time < range.RangeEnd
             select r;