Viacheslav Gostiukhin
Viacheslav Gostiukhin

Reputation: 301

LINQ: events grouped by time

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?

Upvotes: 2

Views: 351

Answers (2)

Bonshington
Bonshington

Reputation: 4032

.GroupBy(obj => long.Parse(obj.time.ToString("yyyyMMddHHmmss")) /5 )

use datetime.ToString() with format to gen number for each second then / 5 for every 5 sec

Edit: I wasn't quite sure what u r looking but i tried this and it works

var now = DateTime.Now;

            Console.WriteLine(now.ToString("yyyyMMddHHmmss"));

            Enumerable.Range(0, 57)
                .Select(offset => now.AddSeconds(offset))
                .GroupBy(interval => long.Parse(interval.ToString("yyyyMMddHHmmss")) / 5)
                .ToList()
                .ForEach(g => Console.WriteLine("{0}: {1} - {2}", g.Count(), g.Min().ToString("yyyyMMddHHmmss"), g.Max().ToString("yyyyMMddHHmmss")));

            Console.ReadKey();

Here is the sample output

20120125144606
4: 20120125144606 - 20120125144609
5: 20120125144610 - 20120125144614
5: 20120125144615 - 20120125144619
5: 20120125144620 - 20120125144624
5: 20120125144625 - 20120125144629
5: 20120125144630 - 20120125144634
5: 20120125144635 - 20120125144639
5: 20120125144640 - 20120125144644
5: 20120125144645 - 20120125144649
5: 20120125144650 - 20120125144654
5: 20120125144655 - 20120125144659
3: 20120125144700 - 20120125144702

Sample datetime is groupped with 5 sec interval. eg second from 10 - 14. If u want 11 - 15 u could add 1 sec before devide :)

Upvotes: 1

Ani
Ani

Reputation: 113412

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:

// Needs argument-checking, but you'll need another method to do it eagerly.
public static IEnumerable<List<T>> GroupByConsective<T>
      (this IEnumerable<T> source, Func<T, T, bool> prevNextPredicate)
{
    var currentGroup = new List<T>();

    foreach (var item in source)
    {
        if (!currentGroup.Any() || prevNextPredicate(currentGroup.Last(), item))
            currentGroup.Add(item); // Append: empty group or nearby elements.
        else
        {
            // The group is done: yield it out
            // and create a fresh group with the item.
            yield return currentGroup;
            currentGroup = new List<T> { item };
        }
    }

   // If the group still has items once the source is fully consumed,
   // we need to yield it out.
   if(currentGroup.Any())
     yield return currentGroup;
}

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:

using (var db = new DbContainer())
{
   var groups = db.Table
                  .Select(row => row.Time)
                  .GroupByConsecutive((prev, next) => next.Subtract(prev)
                                                          .TotalSeconds <= 5)
                  .Take(count)
                  .ToList();

  // Use groups...

}

Upvotes: 3

Related Questions