The most likely reason for this method being slow is the .Count() call, which immediately lists the sequence to determine the number of elements.
You will probably be better off explicitly checking the criteria and tracking the counts, rather than using Where() and Count() several times.
In general, this method lists the sequence a lot. You can experience good speed if you call .ToList() to enumerate the sequence once, and then do your operations in the generated list. (Note that this will not work if you plan to use this method for sequences of infinite length.)
Update . You are testing >= sequenceSize , although window.Count() == sequenceSize . In other words, you just need All() :
if (window.All(x => predicate(x))) yield return window;
Not sure how much this will help, but at least semantically understandable.
Further editing . Consider this method:
public static IEnumerable<IEnumerable<T>> FindSequenceConsecutive<T>(this IEnumerable<T> sequence, Predicate<T> predicate, int sequenceSize) { List<T> list = sequence.ToList(); List<bool> matchList = list.Select(x => predicate(x)).ToList(); int start = 0; int count = list.Count; while (start + sequenceSize <= count) { var range = matchList.GetRange(start, sequenceSize); if (range.All(x => x)) yield return list.GetRange(start, sequenceSize); start++; } }
It evaluates the sequence once, and then breaks up the list of necessary ones.
source share