LINQ - 如何在接下来的三个工作日中排除表中的日期?

时间:2011-07-25 18:28:48

标签: linq

我需要找到调度应用程序的下三个可用工作日。可用的内容取决于表中的排除日期。所以...只要日期不在我的桌子而不是星期六或星期日,我想要接下来的三个。我想找到一种有效的方法。

我需要返回List<DateTime>。该表很简单 - ExcludedDates有一个ID和一个带有排除日期的DateTime。

我想要一个单独的LINQ查询表达式,但无法弄清楚...多亏了所有提前并且我道歉,如果这是微不足道的或显而易见的 - 它不适合我。

4 个答案:

答案 0 :(得分:8)

试试这个......

  DateTime start = DateTime.Now.Date;
  var result = Enumerable.Range(1, 10) // make this '10' higher if necessary (I assume you only exclude non-workingdays like Christmas and Easter)
                    .Select(offset => start.AddDays(offset))
                    .Where(date => !( date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek== DayOfWeek.Sunday))
                    .Where(d=> !exceptionTable.Any(date => date == d))
                    .Take(3).ToList();

答案 1 :(得分:0)

这假设一个月是合理的,具体取决于您的排除日期。

        DateTime date = DateTime.Today;
        // first generate all dates in the month of 'date'
        var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
        // then filter the only the start of weeks
        var results = (from d in dates
                       where d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Saturday && !excludes.Any(i => i.DateTime.Date == d.Date) && date < d
                       select d).Take(3);

答案 2 :(得分:0)

List<DateTime> result = (from i in Enumerable.Range(1, excludeTable.Rows.Count + 6)
        let date = inputDate.AddDays(i)
        where date.DayOfWeek != DayOfWeek.Saturday &&
              date.DayOfWeek != DayOfWeek.Sunday &&
              !excludeTable.Rows.Cast<DataRow>().Select(r => (DateTime) r["ExcludeDate"]).Contains(date)
        select date).Take(3).ToList();

excludeTable.Rows.Count + 6将涵盖最糟糕的情况,即您跳过excludeTable中的所有内容,然后您必须跳过另一个周末。

答案 3 :(得分:0)

var excludedList = new List<long>() { DateTime.Parse("2011-07-27").Ticks };

var week = new List<long>(){
                DateTime.Now.Date.Ticks, 
                DateTime.Now.Date.AddDays(1).Ticks,
                DateTime.Now.Date.AddDays(2).Ticks,
                DateTime.Now.Date.AddDays(3).Ticks,
                DateTime.Now.Date.AddDays(4).Ticks,
                DateTime.Now.Date.AddDays(5).Ticks,
                DateTime.Now.Date.AddDays(6).Ticks,
                DateTime.Now.Date.AddDays(7).Ticks,
                DateTime.Now.Date.AddDays(8).Ticks
            };

var available = (from d in week.Except(excludedList)
                 where new DateTime(d).DayOfWeek != DayOfWeek.Saturday && new DateTime(d).DayOfWeek != DayOfWeek.Sunday
                 select new DateTime(d)).Take(3);

foreach (var a in available)
     Console.WriteLine(a.ToString());