Is there any dedicated Interactive Extensions method which will produce the last n elements before some condition is encountered?
For instance for the array src
, I'd like to get the element 99 plus 2 elements right before it:
var src = new[] { 1, 2, 3, 4, 99, 5, 6, 7, 99, 8, 9, 10, 99 };
{{3, 4, 99}, {6, 7, 99}, {9, 10, 99}}
I've сome up with the following code, but was wondering if there's a dedicated method or combination of methods to do this.
var result = src.Buffer(3, 1).Where(i => i.Count == 3 && i.Last() == 99);
So, I was a curious about other solutions as well and decided to play around with it. I did come up with a different solution using windowing:
With this solution
windows
is now anIObservable<IObservale<int>>
. The marble diagram looks something like this (I hope it makes sense, I'm waffling on the best way to represent an observable of observable):At first glance the behavior looks the same as your solution but after playing around with it I realized it behaves quite differently when you have overlapping widows.
If you use this
src
instead:Your solution produces:
While the windowing solution yields this:
It doesn't seem that different until you call
SelectMany
on both results. Then yours looks like this:But the windowing solution interleaves the observables (which makes sense):
One thing to consider when using the
Buffer
solution is that each buffer requires copying the buffer to a new list before it is returned. So, it's possible the windowing solution could perform better in some scenarios. I admit that I don't understand the inner workings of observables as well as I do enumerables so I would have to do some testing to be sure.Anyway, it was fun to play around with and it could be a viable solution depending on what your end goal is.