LINQ - how to get the next three business days excluding dates in the table?

I need to find the next three available business days for a planning application. What is available depends on the dates excluded in the table. So ... until the date is at my desk, and not on Saturday or Sunday, I want the following three. I would like to find an effective way to do this.

I need to return a List<DateTime> . The table is simple: ExcludedDates has an identifier and DateTime with an excluded date.

I would like to have one LINQ query expression, but I can't figure it out ... thanks to everyone in advance, and I apologize if this is trivial or obvious - this is not for me.

+6
source share
4 answers

Try it...

  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(); 
+8
source

This suggests that the month will be reasonable depending on your excluded dates.

  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); 
0
source
 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 should cover the worst case where you skip every thing in excludeTable, and then you need to skip another weekend.

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

Source: https://habr.com/ru/post/893516/


All Articles