This code seeks groups of events that occurred together.
Max 5 seconds between them. And more then 5 seconds between groups.
Update: Group is List of DateTimes. One group contains DateTimes between which less than 5 seconds. DateTimes which occured more then 5 second placing to next group.
public static List<List<DateTime>> GetGroups(int count)
{
var groups = new List<List<DateTime>>();
groups.Add(new List<DateTime>());
using (var db = new DbContainer())
{
foreach (var row in db.Table)
{
if (!groups.Last().Any() || (groups.Last().Any() && (row.Time - groups.Last().Last()).TotalSeconds <= 5))
{
groups.Last().Add(row.Time);
}
else if (groups.Count < count)
{
groups.Add(new List<DateTime>());
groups.Last().Add(row.Time);
continue;
}
if (groups.Count == count)
{
break;
}
}
}
return groups;
}
Can I implement the same algoritm in LINQ in one or two expressions?
Essentially, the only tricky part about your query that’s hard to express with standard LINQ to Objects operators is grouping items based on how close consecutive ones are to each other.
For this alone, I would use an iterator block:
For everything else (projection, capping the number of groups, materializing to a collection), standard LINQ to Objects will work fine. And so your query becomes: