(C #) LINQ to get next weekday

less than 1 minute read

Introduction

I wondered if I could write a clean code to get the next weekday in C # and tried it in LINQ.
I would appreciate it if you could comment if you have better code.

environment

Windows 10
Visual Studio 2019

reference

I got an idea from this description.
https://tercel-tech.hatenablog.com/entry/2014/02/08/183432

code

It is an extension method of DateTime.

NextWeekday.cs


public static DateTime NextWeekday(this DateTime date,List<DateTime> holidayList = null) {
	//Get the closest business day up to 100 days later
	//100 is OK with a suitable large number
	DateTime next = Enumerable.Range(1, 100).Select(x => date.AddDays(x)).First(
		x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday && !(holidayList?.Contains(x) ?? false)
	);
	return next;
}

important point

The holiday list is AND DateTime.Today brought from somewhere, and the time part is assumed to be 0.
It simply determines the dates that are “not Saturday & not Sunday & not on the holiday list”.

Conclusion (future development)

Next is the holiday list, but I’d like to take a look at the Google Calendar API.
I’m thinking of trying it with reference to here.
https://blog.divakk.co.jp/entry/holidays

Tags: ,

Updated: