选择具有多个句点时间字段的行

时间:2016-08-08 05:14:37

标签: c# asp.net asp.net-mvc datatable

我使用asp.net mvc和c# 我有数据表有很多列,一列有'时间'和sotred数据像这种格式

14
16:30
17:05
...

在视图中我有过滤时间,用户可以从复选框中选择多个时间, 我的过滤器复选框是

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

现在我想从数据表中过滤

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(); 

我的问题是,我不知道用户有多少通过时间,如果只是通过一次它很容易,但我不知道经过了多少时间

我如何编辑代码以便随时和任何时间接受?

谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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;

确保处理解析为int可能失败的案例

在输入范围的集合中,您可以执行以下操作:

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;

答案 1 :(得分:0)

您应该考虑以非字符串格式存储时间。直接比较是困难的(即&#34; 17&#34;&lt;&#; 9&#34;但是17&gt; 9)。请记住,程序是算法+数据结构。

var data = new[]
{
    new {Time = "6", Other = "Time6"},
    new {Time = "14", Other = "Time14"},
    new {Time = "16:30", Other = "Time1630"},
    new {Time = "17:05", Other = "Time1705"}
};

string[] inputs = {"4 - 8", "17 - 21"};

var result = from d in data
             let hour = Convert.ToInt32(d.Time.Split(':')[0])
             where inputs.Select(i =>
             {
                 var ranges = i.Split('-');
                 return new
                 {
                     From = Convert.ToInt32(ranges[0].Trim()),
                     To = Convert.ToInt32(ranges[1].Trim())
                 };
             }).Any(range => hour >= range.From && hour < range.To)
             select d;