【发布时间】:2015-01-20 17:22:32
【问题描述】:
我有一个包含事件名称、时间戳和持续时间(时间跨度)的类列表。有许多重复的事件名称。我想按事件名称合并它们并添加它们的持续时间并保留最早的时间戳,除非事件具有特定名称。即,删除重复的事件名称,为类似的事件名称添加持续时间,并保留偶数名称中最早的时间戳。
有没有更好的方法来做到这一点?可能与 Linq 一起使用?
这是我尝试过的,似乎没有正确合并(仍有重复但数量较少)
班级:
public class eventRecords
{
public DateTime TimeStamp { get; set; }
public string Event { get; set; }
public TimeSpan Duration { get; set; }
}
我的尝试:
// allEventList is already sorted by TimeStamp, so my thinking is adding
// the first occurrence of an event to newList will keep the earliest
// TimeStamp in eventRecrods for that event
// Also - the duplicates are almost all consecutive in allEventList
var newList = new List<eventRecords>();
for (int ii = 0; ii < allEventList.Count; ii++ )
{
newList.Add(allEventList[ii]);
if((ii + 1) < allEventList.Count && allEventList[ii] != keyword)
{
if(allEventList[ii].Event == allEventList[ii+1].Event)
{
newList.Last().Duration = newList.Last().Duration+ allEventList[ii + 1].Duration;
ii = ii + 1;
}
}
}
例如,如果 allEventList 包含:
Event = "Action 1", TimeStamp = 08:00, Duration = TimeSpan.FromMinutes(1);
Event = "Action 1", TimeStamp = 09:00, Duration = TimeSpan.FromMinutes(1);
Event = "Action 1", TimeStamp = 10:00, Duration = TimeSpan.FromMinutes(1);
Event = "KeyWord", TimeStamp = 11:00, Duration = TimeSpan.FromMinutes(1);
Event = "Action 2", TimeStamp = 12:00, Duration = TimeSpan.FromMinutes(1);
Event = "Action 2", TimeStamp = 13:00, Duration = TimeSpan.FromMinutes(1);
newList 应包含:
Event = "Action 1", TimeStamp = 08:00, Duration = TimeSpan.FromMinutes(3);
Event = "KeyWord", TimeStamp = 11:00, Duration = TimeSpan.FromMinutes(1);
Event = "Action 2", TimeStamp = 12:00, Duration = TimeSpan.FromMinutes(2);
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
这绝对可以用 linq 完成,但我并不完全清楚您希望如何聚合这些数据。您能否在帖子中添加一个包含一些示例数据的示例?
-
感谢约翰桑德斯。我更新了一个示例@pquest。
-
@Jamiec 打败了我。这将工作