プログラム 技術

C#で等間隔の時間ごとに集計する

8時間前から現時刻までの30分間隔で各アイテムの時間を元に集計する必要があり、その際のメモとなります。今回は1時間の30分刻み版と実行時間からの30分刻み版の2種類を紹介します
実装方法としてはそんなに難しくないものでした

時刻を取得する

1時間の30分刻み版

対象の時刻を分とそれ以外の年月日時をそれぞれ保持します

DateTime slotStartTime = new DateTime(itemCreateTime.Year, itemCreateTime.Month, itemCreateTime.Day, itemCreateTime.Hour, 0, 0);
int minutes = itemCreateTime.Minute;

実行時間からの30分刻み版

実行時刻から8時間前を求め、時間区切り用の配列に30分ごとの時間を格納していきます

 // 現時刻から8時間前を取得
 DateTime eightHoursAgo = dateTime.AddHours(-8);

 // 時間区切り用の配列作成
 DateTime currentTimeSlot = eightHoursAgo;
 List<DateTime> timeSlots = new List<DateTime>();
 while (currentTimeSlot < dateTime)
 {
     timeSlots.Add(currentTimeSlot);
     currentTimeSlot = currentTimeSlot.AddMinutes(30);
 }

各30分ごとに格納する

1時間の30分刻み版

取得した分が30分より前か後かで判断してカウント

// 30分より前か後か判定する
int slotIndex = minutes / 30;
DateTime slotKey = slotStartTime.AddMinutes(slotIndex * 30);

if (!slotCounts.ContainsKey(slotKey))
{
    slotCounts[slotKey] = 1;
}
else
{
    slotCounts[slotKey]++;
}

実行時間からの30分刻み版

上記で求めたスロットタイムに該当するかどうかを判定してカウント

foreach (DateTime timeSlot in timeSlots)
{
    if (itemCreateTime >= timeSlot && itemCreateTime < timeSlot.AddMinutes(30))
    {
        if (!slotCounts.ContainsKey(timeSlot))
        {
            slotCounts[timeSlot] = 1;
        }
        else
        {
            slotCounts[timeSlot]++;
        }
        break; // アイテムは1つの時間スロットにのみカウントされる
    }
}

最期に

今回紹介したコードを以下のGitHubにアップしていますので参考にしてください

サンプル
BlogSampleCodeProjects/Aggregation at main · nasuton/BlogSampleCodeProjects · GitHub
BlogSampleCodeProjects/Aggregation at main · nasuton/BlogSampleCodeProjects · GitHub

Project for sample code used in the blog.(Blogで記載しているサンプルコード ...

続きを読む

-プログラム, 技術
-