在列表中<DateTime>具有相同日期时间的地方添加分钟



我有以下列表:

List<DateTime> list =
new [] { "12:00", "12:00", "12:00", "12:30", "12:30", "14:00" }
.Select(DateTime.Parse)
.ToList();

我需要一些可以通过这种方式制作此列表的功能:

{ 12:00, 12:01, 12:02, 12:30, 12:31, 14:00 }

因此,如果有相同的DateTime我应该为每个分钟增加 1 分钟。

假设times按升序排序,这应该可以工作:

private static IEnumerable<DateTime> NewTimes(IEnumerable<DateTime> times)
{
var current = DateTime.MinValue;
foreach (var time in times)
{
if (time > current) current = time;
yield return current;
current = current.AddMinutes(1);
}
}

您可以使用LINQ 并像这样执行此操作(假设时间戳的类型为DateTime)

public static IEnumerable<DateTime> MakeUnique(IEnumerable<DateTime> timestamps)
{
return timestamps.GroupBy(t => t).SelectMany(g => g.Select((t, i) => t.AddMinutes(i)));
}

它的工作原理是首先将时间戳分组到具有相同时间戳的组中。然后,对于每个组,它将组视为列表,并添加 x 分钟数,其中 x 是列表中的索引。因此,第一个添加 0 分钟,第二个添加 1 分钟,依此类推。然后,它使用 SelectMany 将较小的列表展平为单个列表。

如果你愿意使用 NuGet "System.Interactive" 来获取枚举的Scan扩展方法,那么这也可以:

IEnumerable<DateTime> output =
list
.Scan((a, x) => x > a ? x : a.AddMinutes(1.0))
.StartWith(list.First());

这可以通过.Aggregate完成工作:

List<DateTime> list =
new [] { "12:00", "12:00", "12:00", "12:30", "12:30", "14:00" }
.Select(DateTime.Parse)
.ToList();
List<DateTime> output =
list.Skip(1).Aggregate(list.Take(1).ToList(), (a, x) =>
{
a.Add(a.Last() >= x ? a.Last().AddMinutes(1.0): x);
return a;
});

这给了我:

{ 12:00, 12:01, 12:02, 12:30, 12:31, 14:00 }

最新更新