I have a 24 hour "sliding window" sequence of "start" and "stop" events in memory comming from an iOT device.

I'm only interrested in finding "stop" events followed by "start" events in order to determine that the object is offline between these two events.

If I only have a start event, the device is considered offline before and online after.

If I only have a stop event, the device is considered online before and offline after.

This seems a standard pattern in programing but I can't figure a clever way to do that properly given the tools at my disposal, such as LINQ for instance.

What would be the best way to achieve this goal?

EDIT: I'd like to get a list of tuples of "stop" and "start" objects as a result.

  • If the data is in memory, you can just walk back the array of events to find the previous offline event?
    – Martin K
    Feb 13, 2020 at 23:27

1 Answer 1


If I understand your question correctly, you want to filter a list based on the next item in the list instead of the item itself, i.e. in pseudocode:

if(items[i] == stop && items[i + 1] == start)
    return items[i];

This question focuses on how to observe the previous item, but it's essentially doing the same thing and can be tailored to your purpose. All I've changed is the names of the properties, i.e. (previous+current) to (current+next):

// Make sure the events are in chronological order
events = events.OrderBy(e => e.EventDate);

var stopsbeforestarts = 
        // take the ordered events
        // pair them with the next event in the chronological sequence
            .Zip(events.Skip(1), (item, nextItem) => (item, nextItem))
        // filter for (stop+start) pairs
            .Where(zip => zip.item == stop && zip.nextItem == start)
        // select the stop from each remaining pair
            .Select(zip => zip.item);

Note that I simplified your comparison logic to zip.item == stop && zip.nextItem == start because I don't know the exact structure of your object. Implement this predicate as you need it.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.