使用Linq获取日期范围内不存在的天数

时间:2016-06-22 01:48:01

标签: c# linq asp.net-mvc-3

我得到了一份日期列表,可以像

一样出席
06/01/2012
06/02/2012
06/03/2012
06/06/2012
06/07/2012
06/08/2012
06/10/2012
06/13/2012
06/14/2012
06/15/2012

我有这个日期范围

 06/01/2012-06/15/2012

如何使用linq ..

获取不在列表中但属于日期范围的日期

2 个答案:

答案 0 :(得分:2)

您可以这样做:

var dateList = new List<DateTime>
{
    new DateTime(2012, 06, 01),
    new DateTime(2012, 06, 02),
    //..etc
};

var startDate = new DateTime(2012, 06, 01);
var endDate = new DateTime(2012, 06, 15);

var dateRange =
    Enumerable.Range(0, (int)(endDate - startDate).TotalDays + 1)
    .Select(i => startDate.AddDays(i));

var datesNotMatched = dateRange.Except(dateList);

答案 1 :(得分:2)

inputDateList为表示输入日期的字符串列表,AttendanceDate日期时间列表对应于输入字符串。让我用dateRangeStart来表示范围End的开始范围和dateRangeEnd。然后下面的代码将过滤dateRangeStart - dateRangeEnd范围内的inputDateList。

DateTime inDate;
DateTime dateRangeStart;
DateTime dateRangeEnd;
List<string> inputDateList = new List<string>(){"06/01/2012",
                                          "06/02/2012",
                                          "06/03/2012",
                                          "06/06/2012",
                                          "06/07/2012",
                                          "06/08/2012",
                                          "06/10/2012",
                                          "06/13/2012",
                                          "06/14/2012",
                                          "06/17/2012"};

List<DateTime?> AttendanceDate = inputDateList.Select(x => DateTime.TryParseExact(x, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out inDate) ? inDate : (DateTime?)null)
                                              .ToList();

DateTime.TryParseExact("06/01/2012", "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateRangeStart);
DateTime.TryParseExact("06/15/2012", "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateRangeEnd);

List<DateTime?> datesInRange = AttendanceDate.Where(x => x >= dateRangeStart && x <= dateRangeEnd).ToList();

datesInRange将是必需的日期列表