如何解决在列表<DateTime>中添加具有相同日期时间的分钟
我有以下列表:
List<DateTime> list =
new [] { "12:00","12:00","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: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 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。