0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

(C#)次の平日を取得するLINQ

Last updated at Posted at 2020-09-24

はじめに

C#で、次の平日を取得するコードをきれいに書けないかなと思ってLINQで試してみました。
もっといいコードがあればコメントいただけると嬉しいです。

環境

Windows 10
Visual Studio 2019

参考

こちらの記載にアイデアをもらいました。
https://tercel-tech.hatenablog.com/entry/2014/02/08/183432

コード

DateTimeの拡張メソッドとしています。

NextWeekday.cs
public static DateTime NextWeekday(this DateTime date,List<DateTime> holidayList = null) {
	// 100日後までの間で最も近い営業日を取得
	// 100は適当な大きな数値でOK
	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;
}

注意点

祝日リストはどこかから持ってくる AND DateTime.Todayなどで時刻部分は0の前提です。
単純に、「土曜日でない & 日曜日でない & 祝日リストに入ってない」日付を順に判定しています。

おわりに (今後の展開)

次は祝日リストですが、Google Calendar APIを調べてみたいと思います。
ここを参考にして試してみようと思っています。
https://blog.divakk.co.jp/entry/holidays

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?