[C#] Listに格納されている日付から現在日時に一番近いでデータを比較し取得する方法
2022-06-07

目次
はじめに
List<DateTIme>に日時のリストが格納されており、現在の日時に一番近い日付を取得する方法を備忘録として残します。
本処理の実行結果は、2020年5月1日に実行した結果となります。
サンプルコード
早速、サンプルコードを書いてみます。
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
var dates = new List<DateTime>
{
new DateTime(2014, 1, 1),
new DateTime(2015, 1, 1),
new DateTime(2016, 1, 1),
new DateTime(2017, 1, 1),
new DateTime(2018, 1, 1),
new DateTime(2019, 1, 1),
new DateTime(2020, 3, 1),
new DateTime(2020, 4, 29),
new DateTime(2020, 4, 30),
new DateTime(2020, 5, 2),
new DateTime(2020, 5, 3)
};
// for文を利用する場合
Console.WriteLine(ReturnClosest(dates));
// Linqを使う場合
var minDate = dates.OrderBy(x => Math.Abs((DateTime.Now - x).TotalSeconds)).First();
Console.WriteLine(minDate);
}
public static DateTime ReturnClosest(List<DateTime> dateTimes)
{
//Establish Now for simpler code below
var now = DateTime.Now;
//Start by assuming the first in the list is the closest
var closestDateToNow = dateTimes[0];
//Set up initial interval value, accounting for dates before and after Now
TimeSpan shortestInterval = now > dateTimes[0] ? now - dateTimes[0] : dateTimes[0] - now;
//Loop through the rest of the list and correct closest item if appropriate
//Note this starts at index 1, which is the SECOND value, we've evaluated the first above
for (var i = 1; i < dateTimes.Count; i++)
{
TimeSpan testinterval = now > dateTimes[i] ? now - dateTimes[i] : dateTimes[i] - now;
if (testinterval < shortestInterval)
{
shortestInterval = testinterval;
closestDateToNow = dateTimes[i];
}
}
//return the closest Datetime object
return closestDateToNow;
}
}
}
実行結果は下記となります。
for文バージョンもLinqバージョンも両方期待値が出力されました。
2020/05/02 0:00:00
2020/05/02 0:00:00
是非ためしてみてください。
関連記事
[C#] ICompareインターフェースを使用して2つのListを比較する方法
はじめに Unitテスト時に2つのList<T>の比較をICompareイ ...
[C#] 性能改善のためにList型の大容量データを保存する場合はSqlBulkCopyを利用する
はじめに ユーザ定義型としてList<T>を利用するケースは多々あります。 ...
C#] Base64エンコードおよびBase64デコードまとめ
はじめに Base64とは、マルチバイと文字列やバイナリデータをテキスト形式に変 ...
[C#] Windows Formにてタイトルバーなしのフラットなおしゃれフォームを作成する方法
はじめに C#でWindows Formアプリケーションを作成する際に、もともと ...
[C#] シンプルにMD5やSHA256などでハッシュ値を計算し文字列として取得する
はじめに テキストやファイルが改ざんされていないかをチェックするのに適しているハ ...