如何在提供搜索条件时从列表中选择日期范围

时间:2013-11-21 12:56:44

标签: c# linq

   DateInfo[] dateInfo= GetDateInfo();

   DateInfo[] searchDates  = null;
   DateTime dtfrom = DateTime.Parse(txtFromDate.Text);
   DateTime dtTo = DateTime.Parse(txtToDate.Text);
   searchDates = dateInfo.Where(p => p.AddDate >= dtfrom || p.AddDate < dtTo).ToArray<DateInfo>();

如果列表包含

11/17/13,11/18/13,11/19/13,11/19/13,11/19/13,11/20/13,11/20/13 

我输入了

11/17/13 to 11/19/13 

它应该返回

11/17/13,11/18/13,11/19/13,11/19/13,11/19/13

3 个答案:

答案 0 :(得分:3)

||替换为&&

searchDates = dateInfo.Where(p => p.AddDate >= dtfrom && p.AddDate <= dtTo)
                      .ToArray();

答案 1 :(得分:1)

searchDates = dateInfo
   .Where(p => p.AddDate >= dtfrom && p.AddDate <= dtTo)
   .ToArray<DateInfo>();

在这种情况下,将强制过滤介于两者之间的日期,而您的条件将涵盖所有内容。

答案 2 :(得分:1)

感谢您的回答。通过编写此查询解决了我的问题

searchDates  = dateInfo.Where(p => (p.AddDate.Date.Year >= dtfrom.Date.Year && p.AddDate.Date.Month >= dtfrom.Date.Month && p.AddDate.Date.Day >= dtfrom.Date.Day) && (p.AddDate.Date.Year <= dtTo.Date.Year && p.AddDate.Date.Month <= dtTo.Date.Month && p.AddDate.Date.Day <= dtTo.Date.Day)).ToArray<DateInfo>();